我以前在 Java 中使用链表有很多经验,但我似乎对 C++ 中的这种简单尝试感到困惑。我在运行时遇到分段错误,据我了解,这与分配空指针有关,但我对解决方案不知所措。
编辑:谢谢大家非常有帮助的回复。该代码现在正在运行,但正在尝试使用
delete p;
在linkedList::addNode 的末尾会导致运行时出现分段错误。只是好奇是否有人知道这是为什么?
这是我更新的代码:
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node * next;
Node(int x){
data = x;
next = NULL;
}
Node(int x, Node * y){
data = x;
next = y;
}
};
class linkedList{
Node *head;
public:
linkedList(){
head = NULL;
}
void addNode(int value){
Node *p;
if(head == NULL)
head = new Node (value, NULL);
else{
p=head;
while(p->next !=NULL)
p=p->next;
p->next = new Node (value, NULL);
}
}
void print(){
Node * p;
p = head;
while(p != NULL){
cout << p->data << "\n";
p = p->next;
}
}
};
int main(void){
linkedList test;
test.addNode(4);
test.addNode(76);
test.addNode(12);
test.print();
return(0);
}