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);
return c->next
to return head
in 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->next
to be evaluated at a particular time (right before calling the last append()
. But that is not guaranteed.
When you're passing head->next
- its before changing it with head->append
. I'm afraid you're confusing the order of writing with the order of execution.
In this case you're changing the value and reading it in the same execution statement, that's undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With