Could someone please help me understand this algorithm (for a singly linked list)?
Author |
Message |
s3a
|
Posted: Sun Jan 15, 2012 10:26 pm Post subject: Could someone please help me understand this algorithm (for a singly linked list)? |
|
|
Could someone please help me understand this algorithm by explaining each line to me?:
void reverse(){
SNode tmp;
SNode newHead = null;
while (head != null){
tmp = head.getNext(); // It will be the next head
head.setNext(newHead); // Remove from old list and add to front of new
newHead = head; // Update head of new list.
head = tmp; // Update head of old list.
}
head = newHead; // re-set head reference at end.
}
The above is correct since a teacher wrote it and the question is:
"Using pseudocode or Java (or a mix), write an algorithm for reversing the order of nodes in a singly linked list. You may assume a head and tail reference, and you may directly get and set the next field of any node, but you may not assume any add or remove methods are defined.".
Any input would be GREATLY appreciated!
Thanks in advance! |
|
|
|
|
![](images/spacer.gif) |
Sponsor Sponsor
![Sponsor Sponsor](templates/subSilver/images/ranks/stars_rank5.gif)
|
|
![](images/spacer.gif) |
mirhagk
|
Posted: Sun Jan 15, 2012 11:24 pm Post subject: RE:Could someone please help me understand this algorithm (for a singly linked list)? |
|
|
So what happens is we set newHead to null, and we then go to the list. So long as the head (or rather the current head that we're looking at) is not null, we do the algorithm.
we get the thing the head is pointing at, and store it in temp. We then make it point at whatever newHead is pointing at. For the first case this means that the head of the old list will now point to null in the new list.
then we store the current head in newHead (as it will be what the next element is looking at), we also make the head of the current list equal to the temp (what used to be what it was pointing to) essentially advancing through the array)
Work it out with an example and you should get it. |
|
|
|
|
![](images/spacer.gif) |
|
|