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
reverse
function 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 toprint
in both cases? What does that tell you?EDIT:
Since you said you've found the problem, I'll post the actual solution.
In your
reverse
code, you never update the_head
of the list, but when youreverse
the list, the head does actually change from4
to1
. Since you never update_head
, when you callprint
the second time (after thereverse
call) you start printing at1
, That being the end of the list, that's the only node printed.The solution is to update
_head
when 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):