Sunday, October 12, 2014

Merge a linked list into another linked list at alternate positions

// Merging Two list into single List

 public static ListNode mergeList(ListNode h1, ListNode h2)
 {
  if(h1==null && h2 == null) return null;
  ListNode c1,c2, t1,t2;
  for(c1 = h1, c2 = h2; c1!=null && c2!=null; )
  {
   t1 = c1.next;
   t2 = c2.next;
   
   c2.next = c1.next;
   c1.next = c2;
   
   c1 = t1;
   c2 = t2;
  }
  
  if(c1 == null)
   h2 = c2;
  else
   h2 = null;
   
  return h2;
 }

No comments:

Post a Comment