Created
November 12, 2014 18:23
-
-
Save hsaputra/1112a33c68dd895c52c6 to your computer and use it in GitHub Desktop.
Reverse Linked List
This file contains hidden or 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 Object data; | |
} | |
public static void reverseList ( Node head) { | |
if (head == null || head.next == null) { | |
return; | |
} | |
Node before = null; | |
Node current = head; | |
while (current != null) { | |
// move current.next to before | |
Node next = current.next; | |
current.next = before | |
before = current; | |
current = next; | |
} | |
head = before; | |
} | |
public static Node reverseWithRecursiveList ( Node head) { | |
if (head == null || head.next == null) { | |
return node; | |
} | |
Node before = head; | |
Node current = head.next; | |
return reverse (before, current); | |
} | |
public static Node reverse (Node before, Node current) { | |
if (current == null) { | |
return before; | |
} | |
Node next = current.next; | |
current.next = before; | |
before = current; | |
current = next; | |
return reverse (before, current); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment