Reversing ListNodes
Hello I am trying to write an algorith that Reverses a Linked Lists
Now here is what I have, its a darn pain in the neck!
I am so close, but it just wont work!!
publicstatic ListNode reverseList(ListNode head)
{
ListNode reversed =null;
ListNode temp =new ListNode(head.getValue(), head);// the runner variable
while (temp !=null){
ListNode newNode =new ListNode(temp.getValue(), temp);
newNode.setNext(reversed);
reversed = newNode;
temp = temp.getNext();
}
return reversed;
}
In the main:The linked lists is initialized to 1 2 3 4 5
when i Reverse it should be 5 4 3 2 1
--
the problem is :
mine turns out to be 5 4 3 2 1 1 !!!!
I understand that this doesnt have inadequete information. So, please tell me what else I need to post to make this clear.
[1298 byte] By [
JollyJoea] at [2007-10-2 4:59:13]

:(
Its been like 2 days, and i still havent figured out the answer. This is sad, but please someone help me.. I really would appreciate it.
Here is my ListNode class
public class ListNode
{
private Object value;
private ListNode next;
public ListNode(Object initValue, ListNode initNext)
{
value=initValue;
next=initNext;
}
public Object getValue()
{
return value;
}
public ListNode getNext()
{
return next;
}
public void setValue(Object theNewValue)
{
value=theNewValue;
}
public void setNext(ListNode theNewNext)
{
next=theNewNext;
}
}
> :(
>
> Its been like 2 days, and i still havent figured out
> the answer. This is sad, but please someone help me..
> I really would appreciate it.
>
Sure, we just wanted to make you sweat a little first.
No, just kidding :-)
// Don't create a new instance here:
ListNode temp = new ListNode(head.getValue(), head); // the runner variable
// Use head directly instead. It's ok, because you won't modify head in the following logic:
ListNode temp = head;
// Also (this is not crucial), no need to do this in two steps:
ListNode newNode = new ListNode(temp.getValue(), temp);
newNode.setNext(reversed);
// One step is enough:
ListNode newNode = new ListNode(temp.getValue(), reversed);