Skip to content

Instantly share code, notes, and snippets.

@hkurokawa
Created February 12, 2019 13:23
Show Gist options
  • Save hkurokawa/4efc47a00eec979d598af16260963a5e to your computer and use it in GitHub Desktop.
Save hkurokawa/4efc47a00eec979d598af16260963a5e to your computer and use it in GitHub Desktop.
Reverse a LinkedList
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