Created
May 22, 2012 03:07
-
-
Save kmizumar/2766274 to your computer and use it in GitHub Desktop.
reverse linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Node { | |
public Node next; | |
public String label; | |
public Node(String label, Node next) { | |
this.label = label; | |
this.next = next; | |
} | |
public void dump() { | |
System.out.println(label); | |
if (next != null) { | |
next.dump(); | |
} | |
} | |
public static Node reverse(Node node){ | |
return foo(node, null); | |
} | |
private static Node foo(Node node, Node reversed) { | |
if (node == null) { | |
return reversed; | |
} | |
else { | |
Node tmp = node.next; | |
node.next = reversed; | |
return foo(tmp, node); | |
} | |
} | |
public static void main(String[] args) { | |
Node C = new Node("C", null); | |
Node B = new Node("B", C); | |
Node A = new Node("A", B); | |
Node X = reverse(A); | |
X.dump(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment