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 to print
. One before and one after the reverse. What do you note about the nodes being passed to print
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 you reverse
the list, the head does actually change from 4
to 1
. Since you never update _head
, when you call print
the second time (after the reverse
call) you start printing at 1
, 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):
void LinkedList::reverseList()
{
Node *next=_head;
Node *prev=0;
while(next!=0)
{
Node *tmp=next->_next;
next->_next=prev;
_head = next;
prev=next;
next=tmp;
}
}