class Node {
public int data;
public Node next;
public Node prev;
public Node(int data){
this.data=data;
}
return ""+data;
}
}
/**
* Recursive Pair swapping in a linked list
* @author Prateek
*/
class PairSwapRecursive {
/**
* Recursive Subroutine to swap pairs of nodes of linked list
* @return new Head of the linked list
*/
public Node pairSwap(Node head){
Node curr=head;
Node front=null;
if(curr!=null && curr.next!=null){
front=curr.next;
curr.next = pairSwap(front.next);
front.next=curr;
}
return (front!=null) ? front : curr;
}
public static void main
(String[] args
) { PairSwapRecursive obj = new PairSwapRecursive() ;
Node root = new Node(1) ;
root.next =new Node(2) ;
root.next.next =new Node(3) ;
root.next.next.next =new Node(4) ;
root.next.next.next.next =new Node(5) ;
//root.next.next.next.next.next =new Node(6) ;
Node head=obj.pairSwap(root);
obj.display(head);
}
/**
* Display the nodes of the linked list
*/
public void display(Node root) {
Node tempNode;
tempNode=root;
while(tempNode!=null){
System.
out.
print(tempNode.
data+"-->"); tempNode=tempNode.next;
}
}
}
Y2xhc3MgTm9kZSB7CgoJcHVibGljIGludCBkYXRhOwoJcHVibGljIE5vZGUgbmV4dDsKCXB1YmxpYyBOb2RlIHByZXY7CgkKCXB1YmxpYyBOb2RlKGludCBkYXRhKXsKCQl0aGlzLmRhdGE9ZGF0YTsKCX0KCQoJcHVibGljIFN0cmluZyB0b1N0cmluZygpewoJCXJldHVybiAiIitkYXRhOwoJfQp9Ci8qKgogKiBSZWN1cnNpdmUgUGFpciBzd2FwcGluZyBpbiBhIGxpbmtlZCBsaXN0CiAqIEBhdXRob3IgUHJhdGVlawogKi8KIGNsYXNzIFBhaXJTd2FwUmVjdXJzaXZlIHsKCS8qKgoJICogUmVjdXJzaXZlIFN1YnJvdXRpbmUgdG8gc3dhcCBwYWlycyBvZiBub2RlcyBvZiBsaW5rZWQgbGlzdAoJICogQHJldHVybiBuZXcgSGVhZCBvZiB0aGUgbGlua2VkIGxpc3QKCSAqLwoJcHVibGljIE5vZGUgcGFpclN3YXAoTm9kZSBoZWFkKXsKCQlOb2RlIGN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