Skip to content

Instantly share code, notes, and snippets.

@codyrioux
Last active November 8, 2021 14:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codyrioux/9456476 to your computer and use it in GitHub Desktop.
Save codyrioux/9456476 to your computer and use it in GitHub Desktop.
Linked list class with a recursive reverse function and main method for testing.
public class LinkedList {
public static class Node {
public int data;
public Node next;
}
public static Node reverse(Node head) {
if (head == null || head.next == null) {
return head;
}
Node n = head.next;
head.next = null;
Node rest = reverse(n); // Had a really hard time not calling this in tail position.
n.next = head;
return rest;
}
// Added reverse2 in very late (Would have been midnight your time)
// I was thinking a little more about the problem while I was relaxing,
// and getting the recrsive call
// into tail position. I originally though I would need default arguments, but then
// realized function overloading satisfies the same need for abstraction.
private static Node reverse2(Node head, Node prev) {
Node n = head.next;
head.next = prev;
if (n == null) {
return head;
}
return reverse2(n, head);
}
public static Node reverse2(Node head) {
if (head == null || head.next == null) {
return head;
}
Node n = head.next;
head.next = null;
return reverse2(n, head);
}
public static void main(String[] args) {
Node first = new Node();
Node second = new Node();
Node third = new Node();
first.data = 1;
first.next = second;
second.data = 2;
second.next = third;
third.data = 3;
Node reversed = reverse2(first);
while(reversed != null) {
System.out.println(reversed.data);
reversed = reversed.next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment