【发布时间】:2014-08-12 12:38:02
【问题描述】:
我在用 c++ 编写链接列表实现时遇到了一个问题。每当我尝试添加元素时,我都会收到 Segmentation Fault 错误。
#include <iostream>
class node{
public:
int data;
class node *next;
};
class LinkedList {
public:
node *head;
LinkedList(int num);
void add(int number);
void display();
};
const int null = 0;
LinkedList::LinkedList(int num) {
// TODO Auto-generated constructor stub
std::cout<<"Constructor Called"<<std::endl;
head->data = num;
head->next = null;
std::cout<<"Constructor Call completed"<<std::endl;
}
void LinkedList::add(int num) {
struct node *n=new node;
n->data = num;
n->next = null;
struct node *current = head;
while (current->next != null) {
current = current->next;
}
current->next = n;
}
void LinkedList::display() {
std::cout<<"Display"<<std::endl;
struct node *current = head;
while (current!= null) {
std::cout << current->data << "->";
current = current->next;
}
std::cout << "null"<<std::endl;
}
int main() {
LinkedList l(1);
l.display();
l.add(2);
l.display();
return 0;
}
请查看 gdb 调试日志:节点 n 没有引用任何内存位置。所以无法初始化。如果您需要任何进一步的信息,请告诉我。
提前致谢!
struct node *n=new node;
构造函数调用
构造函数调用完成
SampleCPP.cpp:60 处的断点 1,main ()
60 l.display();
(gdb) 小号
SampleCPP.cpp:48 处的 LinkedList::display (this=0xbffff03c)
48 标准::cout
(gdb) n
51同时(当前!=空){
(gdb) n
52 标准::cout 数据";
(gdb) n
53 当前=当前->下一个;
(gdb) n
51同时(当前!=空){
(gdb) n
55 标准::cout 空
56 }
(gdb) n
SampleCPP.cpp:61 处的 main ()
61 l.add(2);
(gdb) 小号
LinkedList::add (this=0xbffff03c, num=2) at SampleCPP.cpp:38
38 结构节点 *n=新节点;
(gdb) 打印 n
$2 = (节点 *) 0x0
(gdb)
【问题讨论】:
标签: c++ linked-list