我有很多以前使用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);
}
} …Run Code Online (Sandbox Code Playgroud)