下面的朴素代码实现了一个链表,不打印主函数中的所有元素,一切都会好的。然而,LinkedList::printll
函数将触发一个设置错误(海湾合作委员会5.3.0),这个问题涉及到适当的处理头节点我想...链表中的头节点
那么,有没有什么办法让这段代码的工作printll
函数的最小修改?
#include <iostream>
using namespace std;
struct Node{
int value;
Node* next;
};
struct LinkedList{
Node* head= NULL ;
void append(int);
void printll();
};
void LinkedList::append(int data){
Node* cur = head;
Node* tmp = new Node;
tmp->value = data;
tmp->next = NULL;
if(!cur){
cur = tmp; // cur-> head
}
else{
while(cur->next != NULL){
cur = cur->next;
}
cur->next = tmp;
}
std::cout<<cur->value<<std::endl; // cur-> temp
delete tmp; // comment out
}
void LinkedList::printll(){
Node* cur = head;
while(cur->next != NULL){ //
std::cout<<cur->value<<std::endl;
cur = cur->next;
}
}
int main(){
LinkedList LL;
LL.append(5);
LL.append(6);
LL.append(7);
LL.printll(); // --without this, the program is fine
return 0;
}
作为@BoBTFish说,你必须删除'删除TMP;'从你的代码(为什么你'delete'一个'node'刚才添加它到'List'?),并在'printll'中改变'while'循环,建议:'while(cur)' –
我改变了@BoBTFish所提出的所有建议,而且我正在使用GCC 5.3.0进行编译。 ,它仍然segfault ..问题发生在“cur-> next”我猜 – lorniper
@lorniper当我做了我建议的更改,我能够编译和正常运行。你可以发布你的确切代码仍然是残疾人吗? – BoBTFish