fork download
  1. class Node {
  2.  
  3. public int data;
  4. public Node next;
  5. public Node prev;
  6.  
  7. public Node(int data){
  8. this.data=data;
  9. }
  10.  
  11. public String toString(){
  12. return ""+data;
  13. }
  14. }
  15. /**
  16.  * Recursive Pair swapping in a linked list
  17.  * @author Prateek
  18.  */
  19. class PairSwapRecursive {
  20. /**
  21. * Recursive Subroutine to swap pairs of nodes of linked list
  22. * @return new Head of the linked list
  23. */
  24. public Node pairSwap(Node head){
  25. Node curr=head;
  26. Node front=null;
  27.  
  28. if(curr!=null && curr.next!=null){
  29. front=curr.next;
  30. curr.next = pairSwap(front.next);
  31. front.next=curr;
  32. }
  33. return (front!=null) ? front : curr;
  34. }
  35.  
  36. public static void main(String[] args) {
  37. PairSwapRecursive obj = new PairSwapRecursive() ;
  38.  
  39. Node root = new Node(1) ;
  40. root.next =new Node(2) ;
  41. root.next.next =new Node(3) ;
  42. root.next.next.next =new Node(4) ;
  43. root.next.next.next.next =new Node(5) ;
  44. //root.next.next.next.next.next =new Node(6) ;
  45.  
  46. Node head=obj.pairSwap(root);
  47. obj.display(head);
  48. }
  49.  
  50. /**
  51. * Display the nodes of the linked list
  52. */
  53. public void display(Node root) {
  54. Node tempNode;
  55. tempNode=root;
  56. while(tempNode!=null){
  57. System.out.print(tempNode.data+"-->");
  58. tempNode=tempNode.next;
  59. }
  60. System.out.print("null");
  61. System.out.println();
  62. }
  63. }
  64.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
2-->1-->4-->3-->5-->null