Skip to content

Instantly share code, notes, and snippets.

@kmizumar
Created May 22, 2012 03:07
Show Gist options
  • Save kmizumar/2766274 to your computer and use it in GitHub Desktop.
Save kmizumar/2766274 to your computer and use it in GitHub Desktop.
reverse linked list
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