Okay. I am paying around with a simple linked list code.
I keep the head node as public. then I declare a pointer (head2)to store the head node of the first list(first) in the main program. I declare a second list called second, and assign head2 as the head node of the second list. Then I delete head2. I then access the members of "second" (whose head node is deleted) and print them. I expected a segmentation fault. But it works, only printing 0 for the data of the head node. What is puzzling to me is that if the head node is deleted, how is the next pointer of the head node still in memory? (this is accessed by print to traverse through the list.I am using g++ 4.6.1 in Ubuntu.Here is the code:
#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;
}