Merge two sorted linked lists Hackerrank problem solution

Merge two sorted linked lists Hackerrank

You’re given the pointer to the head nodes of two sorted linked lists. The data in both lists will be sorted in ascending order. Change the next pointers to obtain a single, merged linked list which also has data in ascending order. Either head pointer given may be null meaning that the corresponding list is empty.

Input Format
You have to complete the Node* MergeLists(Node* headA, Node* headB) method which takes two arguments – the heads of the two sorted linked lists to merge. You should NOT read any input from stdin/console.

Output Format
Change the next pointer of individual nodes so that nodes from both lists are merged into a single list. Then return the head of this merged list. Do NOT print anything to stdout/console.

Sample Input

1 -> 3 -> 5 -> 6 -> NULL
2 -> 4 -> 7 -> NULL

15 -> NULL
12 -> NULL

NULL
1 -> 2 -> NULL
Sample Output

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
12 -> 15 -> NULL
1 -> 2 -> NULL
Explanation
1. We merge elements in both list in sorted order and output.

Solution

To merge two sorted linked lists, we can proceed by linearly traversing the lists and adding the node with the smaller value to the result and recursing for the remaining lists.

/*
  Merge two sorted lists A and B as one linked list
  Node is defined as 
  struct Node
  {
     int data;
     struct Node *next;
  }
*/
Node* MergeLists(Node *headA, Node* headB)
{
    if (headA == NULL && headB == NULL) return NULL;
else if (headA == NULL) return headB;
else if (headB == NULL) return headA;
 
/*
  Insert Node at the end of a linked list 
  head pointer input could be NULL as well for empty list
  Node is defined as 
  class Node {
     int data;
     Node next;
  }
*/

Node MergeLists(Node list1, Node list2) {
     // This is a "method-only" submission. 
     // You only need to complete this method 
    
    Node dummy = new Node();
    dummy.next=null;
    dummy.data=0;
    
    Node temp= dummy;
    
    while(true)
        {
        
        if(list1==null)
        {    temp.next = list2;
            break;
        }
        else if(list2==null){
            temp.next = list1;
            break;
        }
        else if(list1.data < list2.data)
            {
              
              temp.next=list1;
              list1=list1.next;
             
"""
 Merge two linked lists
 head could be None as well for empty list
 Node is defined as
 
 class Node(object):
 
   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node

 return back the head of the linked list in the below method.
"""
def MergeLists(xs, ys):
    if not ys:
        return xs
    elif not xs:
        return ys
    
    curr = result = None
    
    while xs and ys:
        if xs.data <= ys.data:
            if curr is None:
                curr = Node(xs.data)
                result = curr
            else:
                curr.next = Node(xs.data)
                curr = curr.next
            xs = xs.next
        else:
            if curr is None:
                curr = Node(ys.data)
                result = curr
            else:
                curr.next = Node(ys.data)
                curr = curr.next
            ys = ys.next
            
    if xs:
        curr.next = xs
    elif ys:
        curr.next = ys
              
    return result

}

else{
temp.next=list2;
list2=list2.next;

}
temp=temp.next;
}
return dummy.next;

}

if(headA->data <= headB->data)
headA->next = MergeLists(headA->next, headB);

else {
Node* temp = headB;
headB = headB->next;
temp->next = headA;
headA = temp;
headA->next = MergeLists(headA->next, headB);
}

return headA;
// This is a "method-only" submission.
// You only need to complete this method
}

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

Leave a reply:

Your email address will not be published.