Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created February 1, 2015 09:20
Show Gist options
  • Save dmnugent80/b9b72129673f2c0119dc to your computer and use it in GitHub Desktop.
Save dmnugent80/b9b72129673f2c0119dc to your computer and use it in GitHub Desktop.
Reverse Linked List Recursive
public class LinkedList
{
public static ListNode head = null;
public static void main(String[] args)
{
head = new ListNode(1);
ListNode curr = head;
for (int i = 2; i < 6; i++){
curr.next = new ListNode(i);
curr = curr.next;
}
curr = head;
while (curr != null){
System.out.println(curr.data);
curr = curr.next;
}
curr = recRev(head);
System.out.println("reversed:");
while (curr != null){
System.out.println(curr.data);
curr = curr.next;
}
}
public static ListNode recRev(ListNode curr){
if(curr.next == null){
return curr;
}
ListNode head = recRev(curr.next);
curr.next.next = curr;
curr.next = null;
// propogate the head value
return head;
}
}
// this will become its own file too (and these can be in any order)
public class ListNode
{
public int data;
public ListNode next;
public ListNode(int input)
{
data = input;
next = null;
}
}
/*output
1
2
3
4
5
reversed:
5
4
3
2
1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment