Sometimes the solutions are not quite obvious. Search for an algorithm to reverse a singly linked list using Java and you won't find any good hits except for this code.
public void reverse()
{
Node currentNode, nextNode, loopNode;
if(first == null) return;
currentNode = first;
nextNode = first.next;
loopNode=null;
while(nextNode != null)
{
currentNode.next = loopNode;
loopNode = currentNode;
currentNode = nextNode;
nextNode = nextNode.next;
}
first = currentNode;
first.next = loopNode;
}
This might not be a very intuitive solution at first sight but infact this is a very clever simulation of C/C++ pointers in Java.
read more | digg story
Java - Reverse a singly linked list
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment