好吧。我用一个简单的链接列表代码付款。简单链接列表代码上的奇怪结果
我把头节点保持公开。然后我声明一个指针(head2)来存储第一个列表的头节点(第一个)到主程序中。我声明第二个名为second的列表,并将head2指定为第二个列表的头节点。然后我删除head2。然后我访问“第二个”(其头节点被删除)的成员并打印出来。我预料会出现分段错误。 但它的工作原理是,只为头节点的数据打印0。令我费解的是,如果头节点被删除,头节点的下一个指针如何仍然在内存中? (这是由印刷通过list.I遍历访问正在使用克++ 4.6.1在Ubuntu.Here是代码:
#include<iostream>
struct Node
{
int data;
Node* next;
};
class list1
{
public:
list1();
Node* head;
void insert(int);
void print();
};
list1::list1()
{
head=NULL;
}
void list1::insert(int a)
{
Node* newnode=new Node;
newnode->data=a;
newnode->next=head;
head=newnode;
}
void list1::print()
{
Node* dummy=head;
while(dummy)
{
std::cout<<dummy->data<<std::endl;
dummy=dummy->next;
}
}
int main()
{
list1 first;
first.insert(1);
first.insert(2);
first.insert(4);
first.insert(9);
list1 second;
Node* head2=new Node;
head2=first.head;
second.head=head2;
delete head2;
second.print();
return 0;
}
你会做得很好谷歌**“C++未定义的行为”** – WhozCraig 2013-03-27 03:08:39