LinkedList Reversing Help.
Code:
Node first, last;
public class Node{
String value;
Node next;
public Node(String value, Node next){
this.value = value;
this.next = next;
}
}
public void reverse(){
if(first == last){
return;
}
Node newlist = first;
last = first;
Node current = first;
Node next = current.next;
while(next != null){
current = next;
next = current.next;
current.next = newlist;
newlist = current;
}
first = current;
last.next = null;
}
Can anyone please this reverse code to me? I really don't understand how this code works...
Re: LinkedList Reversing Help.
Post the code again adding a comment before every line with what you think it does. We will correct you where you are mistaken.
Re: LinkedList Reversing Help.
To be frankly saying , I just don't understand part starting from while loop.
I know that last = first because the first thing must be in the last but other than that seriously..
Re: LinkedList Reversing Help.
Then, seriously, no one can help you. You can only help yourself. Do not think about what the "task" of the method is, look only at each line of code and say what it does, without regard, at first, to the task of the method.
Before that, however, describe what "first" and "last" are in this class and what "next" is in the Node class.
Re: LinkedList Reversing Help.
Just so you know, this is not "to be mean to you". This is a general skill that a programmer must have and I am simply trying to develop that in you. You must at least try. Even if your assumptions are wrong, post them.
Re: LinkedList Reversing Help.
You are indeed right. Thanks for your advice, after struggling with this code for approx. 2 hours I was able to understand the code.
I think one thing that I could not understand was the
current.next = newList
this is very important because by doing this current can go back of the current.next
and then
current becomes the new list by
newlist = current;
Thanks!