Created
February 12, 2019 13:23
-
-
Save hkurokawa/4efc47a00eec979d598af16260963a5e to your computer and use it in GitHub Desktop.
Reverse a LinkedList
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 ReverseLinkedList { | |
static class Node { | |
int value; | |
Node next; | |
Node(int value, Node next) { | |
this.value = value; | |
this.next = next; | |
} | |
@Override public String toString() { | |
if (next == null) return Integer.toString(value); | |
return value + ", " + next.toString(); | |
} | |
} | |
static Node reverse(Node node) { | |
if (node.next == null) return node; | |
Node head = reverse(node.next); | |
Node n = head; | |
while (n.next != null) n = n.next; | |
n.next = node; | |
node.next = null; | |
return head; | |
} | |
public static void main(String[] args) { | |
Node head = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, null))))); | |
System.out.println(head); // 1, 2, 3, 4, 5 | |
Node reversed = reverse(head); | |
System.out.println(reversed); // 5, 4, 3, 2, 1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment