package dsa.linkedlist;
public class ReverseLinkedListRecursively {
public static void main(String args[]) {
ReverseLinkedListRecursively reverser = new ReverseLinkedListRecursively();
SinglyLinkedList<Integer> originalList = reverser.getLabRatList(10);
System.out.println("Original List : " + originalList.toString());
originalList.start = reverser.reverse(originalList.start);
System.out.println("Reversed List : " + originalList.toString());
}
public Node<Integer> reverse(Node<Integer> list) {
if (list == null || list.next == null)
return list;
Node<Integer> nextItem = list.next;
list.next = null;
Node<Integer> reverseRest = reverse(nextItem);
nextItem.next = list;
return reverseRest;
}
private SinglyLinkedList<Integer> getLabRatList(int count) {
SinglyLinkedList<Integer> sampleList = new SinglyLinkedList<Integer>();
for (int i = 0; i < count; i++) {
sampleList.add(i);
}
return sampleList;
}
}
/*
* SAMPLE OUTPUT Original List : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Reversed List : 9,
* 8, 7, 6, 5, 4, 3, 2, 1, 0
*/