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]
# 1

:(

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;

}

}

JollyJoea at 2007-7-16 1:03:18 > top of Java-index,Java Essentials,New To Java...
# 2

> :(

>

> 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);

happy_hippoa at 2007-7-16 1:03:18 > top of Java-index,Java Essentials,New To Java...
# 3
Oh wow!thanks a lot, But the thing is I still don't understand the difference.Why wasn't the original method not working ?
JollyJoea at 2007-7-16 1:03:18 > top of Java-index,Java Essentials,New To Java...
# 4
Oh never mindI figured it out.Thanks a lot man, I really appreciated it.
JollyJoea at 2007-7-16 1:03:18 > top of Java-index,Java Essentials,New To Java...