Skip to content

Instantly share code, notes, and snippets.

@nissshh
Last active June 25, 2018 13:11
Show Gist options
  • Save nissshh/a4492c2b0e9a1c01fffb0c316a174391 to your computer and use it in GitHub Desktop.
Save nissshh/a4492c2b0e9a1c01fffb0c316a174391 to your computer and use it in GitHub Desktop.
Reverse Linked list using recursion without any DS
package com.mc.examples;
import java.util.LinkedList;
import java.util.ListIterator;
public class MyList {
public static void main(String[] args) {
LinkedList<Integer> l = new LinkedList<>();
for (int i = 0; i < 100; i++) {
l.add(i);
}
LinkedList<Integer> r = new LinkedList<>();
System.out.println(l);
reverseme(l.listIterator(), l.element(), r);
System.out.println(r);
}
private static Integer reverseme(ListIterator<Integer> iterator, Integer curr, LinkedList<Integer> r) {
if (iterator.hasNext()) {
r.add(reverseme(iterator, iterator.next(), r));
}
return curr;
}
}
@nissshh
Copy link
Author

nissshh commented Jun 25, 2018

I was recently interviewed where a panel asked me to reverse a singly linked list without using another data structure. I though with a mix of java and data strucutre knowledge i had and finally sat just after interview to write the solution. i do got some hint from interview to use recursion.

another was is to use pointers to nodes, but in java we cannot implement addressing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment