Last active
June 25, 2018 13:11
-
-
Save nissshh/a4492c2b0e9a1c01fffb0c316a174391 to your computer and use it in GitHub Desktop.
Reverse Linked list using recursion without any DS
This file contains 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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.