/**
* Linked List Node
* @author Prateek
*/
class Node {
public int data;
public Node next;
public Node prev;
public Node(int data){
this.data=data;
}
return ""+data;
}
}
/**
* Swap pair wise node using Iteration
* @author Prateek
*/
class PairSwapIterative {
/**
* Iterative Subroutine to swap pairs of nodes of linked list
* @return new Head of the linked list
*/
public Node pairSwap(Node head){
Node temp=head;
head=head.next; //new head
Node front,back;
while(temp!=null && temp.next!=null)
{
back=temp;
front=temp.next;
back.next=front.next;
front.next=back;
if(temp.next!=null)
temp=temp.next;
if(temp.next!=null)
back.next=temp.next;
}
return head;
}
public static void main
(String[] args
) { PairSwapIterative obj = new PairSwapIterative() ;
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;
}
}
}
LyoqCiAqIExpbmtlZCBMaXN0IE5vZGUKICogQGF1dGhvciBQcmF0ZWVrCiAqLwpjbGFzcyBOb2RlIHsKCglwdWJsaWMgaW50IGRhdGE7CglwdWJsaWMgTm9kZSBuZXh0OwoJcHVibGljIE5vZGUgcHJldjsKCQoJcHVibGljIE5vZGUoaW50IGRhdGEpewoJCXRoaXMuZGF0YT1kYXRhOwoJfQoJCglwdWJsaWMgU3RyaW5nIHRvU3RyaW5nKCl7CgkJcmV0dXJuICIiK2RhdGE7Cgl9Cn0KCi8qKgogKiBTd2FwIHBhaXIgd2lzZSBub2RlIHVzaW5nIEl0ZXJhdGlvbgogKiBAYXV0aG9yIFByYXRlZWsKICovCmNsYXNzIFBhaXJTd2FwSXRlcmF0aXZlIHsKCgkvKioKCSAqIEl0ZXJhdGl2ZSBTdWJyb3V0aW5lIHRvIHN3YXAgcGFpcnMgb2Ygbm9kZXMgb2Ygb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