Possible Duplicate:
Unable to reverse a linked list
I'm trying to reverse a linked list:
void LinkedList::reverseList()
{
Node *next=_head;
Node *prev=0;
while(next!=0)
{
Node *tmp=next->_next;
next->_next=prev;
prev=next;
next=tmp;
}
}
Lets say the list is: 4->3->2->1
When I print the list, I only see 1 (The print function is good).
Any help?
Thanks
Since you said you wanted to find the problem on your own, I'll just give you a hint instead of the solution.
Your
reversefunction works in that it successfully reverses the list. That isn't the problem. You probably have 2 calls toprint. One before and one after the reverse. What do you note about the nodes being passed toprintin both cases? What does that tell you?EDIT:
Since you said you've found the problem, I'll post the actual solution.
In your
reversecode, you never update the_headof the list, but when youreversethe list, the head does actually change from4to1. Since you never update_head, when you callprintthe second time (after thereversecall) you start printing at1, That being the end of the list, that's the only node printed.The solution is to update
_headwhen you reverse the list. The simplest way to do this is to simply update it in each iteration. This may be slightly less efficient than other possible solutions, but it doesn't change the time complexity of the algorithm -- it's still O(n):