I was practicing single linked list in c++ (practicing how to find the beginning node of the circular list), but found the use of operator -> very confusing. I’m using Visual studio 2010 C++ Express
This works perfectly: head->append(2)->append(3)->append(4)->append(5)
But this doesn’t work (to create a circular linked list): head->append(2)->append(3)->append(4)->append(5)->append(head->next)
When I jump in this method and debug, it seems head->next is not passed correctly into the method.
But this works:
Node* tail=head->append(2)->append(3)->append(4)->append(5);
tail->append(head->next);- Or after I change
return c->nexttoreturn headin the two methods,head->append(2)->append(3)->append(4)->append(5)->append(head->next)also works.
What am I missing here? Thank you!
Details of my code is as follows:
void main(){
Node* head=new Node(1);
Node* tail=head->append(2)->append(3)->append(4)->append(5)->append(head->next);
cin.get();
}
class Node{
public:
Node* next;
int data;
bool marked;
Node(int d){
data=d;
marked=false;
next=NULL;
}
Node* append(int d){
Node* c=this;
while(c->next!=NULL){
c=c->next;
}
c->next=new Node(d);
return c->next;
}
Node* append(Node* n){
Node* c=this;
while(c->next!=NULL){
c=c->next;
}
c->next=n;
return c->next;
}
};
You are experiencing undefined behavior.
The problem is that you are expecting
head->nextto be evaluated at a particular time (right before calling the lastappend(). But that is not guaranteed.