27 Jan 2014

Linked List: Pair Swapping (Recursive)

Problem Statement: 
              Perform pair-wise swapping on the given linked list using recursion.

Source Code Link
Solution:

Below is the subroutine implementation for achieving the resultant linked list


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
/**
  * 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;
 }


Please comment and post your suggestion or any modification to the above code.
Happy Coding !!:)

1 comment: