1

I am trying to merge two linked list. I wrote the following code to pick out nodes from ListB and link it to listA at appropriate place. However i am getting null pointer exception and not able to figure out why.. pls help

  Node sortedMerge(Node headA, Node headB) {

     if(headB.data<=headA.data){
         Node temp = headB.next;
         headB.next=headA;
         headA=headB;
        if (temp == null) return headA;
         else return sortedMerge(headA, temp);
     }
     else{
         Node headAtemp = headA;
         while(headA.next.data <headB.data && headA.next!=null){
             headA = headA.next;
         }
         Node next = headA.next;
         Node temp = headB.next;
         //changing links
         headA.next= headB;
         headB.next = next;
         if (temp == null) return headAtemp;
         else return sortedMerge(headAtemp,temp);
     }
   }

The function should return the head of the sorted list.

Denise
  • 898
  • 1
  • 16
  • 30

1 Answers1

1

change the order so that it reads from left to right

while(headA.next!=null && headA.next.data <headB.data ){
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64