fork(1) download
  1. /**
  2.  * Linked List Node
  3.  * @author Prateek
  4.  */
  5. class Node {
  6.  
  7. public int data;
  8. public Node next;
  9. public Node prev;
  10.  
  11. public Node(int data){
  12. this.data=data;
  13. }
  14.  
  15. public String toString(){
  16. return ""+data;
  17. }
  18. }
  19.  
  20. /**
  21.  * Swap pair wise node using Iteration
  22.  * @author Prateek
  23.  */
  24. class PairSwapIterative {
  25.  
  26. /**
  27. * Iterative Subroutine to swap pairs of nodes of linked list
  28. * @return new Head of the linked list
  29. */
  30. public Node pairSwap(Node head){
  31. Node temp=head;
  32. head=head.next; //new head
  33.  
  34. Node front,back;
  35. while(temp!=null && temp.next!=null)
  36. {
  37. back=temp;
  38. front=temp.next;
  39.  
  40. back.next=front.next;
  41. front.next=back;
  42.  
  43. if(temp.next!=null)
  44. temp=temp.next;
  45. if(temp.next!=null)
  46. back.next=temp.next;
  47. }
  48. return head;
  49. }
  50.  
  51. public static void main(String[] args) {
  52. PairSwapIterative obj = new PairSwapIterative() ;
  53.  
  54. Node root = new Node(1) ;
  55. root.next =new Node(2) ;
  56. root.next.next =new Node(3) ;
  57. root.next.next.next =new Node(4) ;
  58. root.next.next.next.next =new Node(5) ;
  59. //root.next.next.next.next.next =new Node(6) ;
  60.  
  61. Node head=obj.pairSwap(root);
  62. obj.display(head);
  63. }
  64.  
  65. /**
  66. * Display the nodes of the linked list
  67. */
  68. public void display(Node root) {
  69. Node tempNode;
  70. tempNode=root;
  71. while(tempNode!=null){
  72. System.out.print(tempNode.data+"-->");
  73. tempNode=tempNode.next;
  74. }
  75. System.out.print("null");
  76. System.out.println();
  77. }
  78.  
  79. }
  80.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
2-->1-->4-->3-->5-->null