【发布时间】:2013-09-12 12:25:53
【问题描述】:
我已经这样做了:
class Node {
//
int key;
Node* next;
public:
//
Node() : key( -1 ), next( NULL ) {}
Node( int i, Node* j ) : key( i ), next( j ) {}
//
~Node() { delete next; }
//
static void head_insertion( Node* & head, int i );
void print_list();
};
void Node::head_insertion( Node* & head, int i ) {
cout << "insert() 1 head = " << head << endl;
// append the current list to n
Node n(i, head);
cout << "address of n = " << &n << endl;
// make n the new head
head = &n;
//
cout << "insert() 2 head = " << head << endl;
}
头部插入不起作用:
insert() 1 head = 0x7fff56821518
address of n = 0x7fff56821518
insert() 2 head = 0x7fff56821518
Segmentation fault: 11
我有两个问题:
-
head_insertion中新创建的节点n与head指向的地址相同。发生了什么事? - 我编写析构函数时认为会递归调用列表中下一个元素的析构函数。这是正确的吗?
【问题讨论】:
-
您正在将一个本地实例变量“添加”到您的列表中。需要动态分配一个新的
Node;不推送本地范围的实例。一旦离开该范围,该对象就消失了,访问它是未定义的行为。 -
你如何调用 head_insertion()
标签: c++ linked-list destructor