【发布时间】:2019-08-14 07:36:39
【问题描述】:
我正在编码在单个 LinkedList 的末尾插入一个节点。程序正在执行而没有任何错误,但在输入第一个数字后会运行无限循环。我在代码中找不到我犯的逻辑错误。任何帮助都将是可观的:)。
这是代码和我尝试过的:
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node* next;
};
node* head = NULL; // empty list
node* temp;
void insert(int x){
temp = (node*)malloc(sizeof(node));
temp -> data = x;
temp -> next = NULL;
if (head == NULL) head = temp;
node* temp1 = head;
// traversing the list
while(temp1 -> next != NULL){
temp1 = temp1 -> next;
}
temp1 -> next = temp;
}
void print(){
node* iterator = head;
while(iterator != NULL){
cout << iterator -> data;
iterator = iterator -> next;
}
}
int main(){
int n, x;
cout << "how many numbers\n";
cin >> n;
for(int i = 0; i < n; i++){
cout << "enter the value";
cin >> x;
insert(x);
print();
}
return 0;
}
我希望输出是一个链表,但 o/p 是无限数量的第一个输入的数字/数据(在本例中为“x”)
【问题讨论】:
-
使用
new分配新节点,并使用构造函数正确初始化成员变量。特别是next必须用NULL进行初始化(或者使用nullptr更好)。 -
这很有趣
Program is executing without any errors但running an infinite loop after entering the very first number. -
@πάνταῥεῖ 用你的方法试过了,还是死循环。你介意在你的机器上执行代码吗?
-
@HikkiGOAT 你介意用调试器检查你的代码吗?
-
@πάνταῥεῖ 哦!所以我必须去看一些关于调试的在线教程。谢谢你的建议:)
标签: c++ linked-list singly-linked-list