class Node {
public Node prev;
public int data;
public Node next;
public Node(int data) {
this.data=data;
}
return ""+this.data ;
}
}
/**
* Reverse Linked List(recursively)
* @author Prateek
*/
class ReverseList {
/**
* Reverse Linked List (recursively)
* @param head
* @return
*/
public Node reverse(Node head){
Node revHead ; // to store the new Head pointer
if( head== null || head.next==null )
return head;
revHead=reverse(head.next) ;
head.next.next = head; // points to itself to create loop
head.next = null; // breaks the loop (old link)
return revHead ;
}
public static void main
(String[] args
) { // 1 -> 2 - > 3 -> 4 -> NUll
ReverseList obj = new ReverseList() ;
Node root = new Node(1) ;
root.next =new Node(2) ;
root.next.next =new Node(3) ;
root.next.next.next =new Node(4) ;
System.
out.
println("Original List :"); obj.display(root);
System.
out.
println("\n\nReversed List :"); obj.display(obj.reverse(root)) ;
}
private void display(Node head) {
Node temp = head ;
while(temp!=null) {
System.
out.
print(temp
+ "\t"); temp=temp.next ;
}
}
}
Y2xhc3MgTm9kZSB7CgoJcHVibGljIE5vZGUgcHJldjsKCXB1YmxpYyBpbnQgZGF0YTsKCXB1YmxpYyBOb2RlIG5leHQ7CgkKCXB1YmxpYyBOb2RlKGludCBkYXRhKQl7CgkJdGhpcy5kYXRhPWRhdGE7Cgl9CgkKCXB1YmxpYyBTdHJpbmcgdG9TdHJpbmcoKXsKCQlyZXR1cm4gIiIrdGhpcy5kYXRhIDsKCX0KfQovKioKICogUmV2ZXJzZSBMaW5rZWQgTGlzdChyZWN1cnNpdmVseSkKICogQGF1dGhvciBQcmF0ZWVrCiAqLwogY2xhc3MgUmV2ZXJzZUxpc3QgewoKCS8qKgoJICogUmV2ZXJzZSBMaW5rZWQgTGlzdCAocmVjdXJzaXZlbHkpIAoJICogQHBhcmFtIGhlYWQKCSAqIEByZXR1cm4KCSAqLwogICBwdWJsaWMgTm9kZSByZXZlcnNlKE5vZGUgaGVhZCl7CgkgICBOb2RlIHJldkhlYWQgOyAvLyB0byBzdG9yZSB0aGUgbmV3IEhlYWQgcG9pbnRlcgoJICAgCgkgICBpZ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