Monday, January 25, 2016

Reverse Linked List Recursive in Java

package DataStructures;

public class LinkedListReverse {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

LinkedList linkedList = new LinkedList(5);
linkedList.next = new LinkedList(4);
linkedList.next.next = new LinkedList(3);
linkedList.next.next.next = new LinkedList(2);
linkedList.next.next.next.next = new LinkedList(1);
System.out.println("original linked list:-" + linkedList.toString());
linkedList = recursiveReverse(linkedList);
System.out.println("Recursively reverse:-" + linkedList.toString());

reverseListIterative(linkedList);

}

public static LinkedList recursiveReverse(LinkedList linkedList) {
if (linkedList == null || linkedList.next == null) {
return linkedList;
}
LinkedList remainingReverse = recursiveReverse(linkedList.next);
LinkedList current = remainingReverse;
while (current.next != null) {
current = current.next;
}
current.next = linkedList;
linkedList.next = null;
return remainingReverse;

}

}

No comments:

Post a Comment