Thursday, September 4, 2014

Pairwise swap/ k elements of a given linked list by changing links

// Comment  Pairwise swaping

 public static LNode altReverse(LNode list){
  
  if(list == null || list.next == null) return list;
  
  LNode oldHead = list;
  
  LNode head = altReverse(list.next.next);
  
  LNode tmp = oldHead.next;
  oldHead.next = head;
  tmp.next = oldHead;
  
  return tmp;
 } 

// Comment  swaping  k elements of a given linked list

 public static LNode altReverse(LNode list, int k) {

  if (list == null)
   return list;

  LNode oldHead = list;
  int i = k;
  while (list != null && i > 0) {
   list = list.next;
   i--;
  }

  LNode head = altReverse(list, k);

  int j = k;
  LNode curr = oldHead, prev = null;
  while (curr != null && j > 0 && i == 0) {
   LNode next = curr.next;
   curr.next = prev;
   prev = curr;
   curr = next;
   j--;
  }

  if (i != 0)
   return oldHead;
  else {
   oldHead.next = head;
   return prev;
  }

 }

No comments:

Post a Comment