Saturday, August 12, 2017

Merge LinkedList

Node mergeLists(Node headA, Node headB) {
     // This is a "method-only" submission.
     // You only need to complete this method
    Node currentA = headA;
    Node currentB = headB;
    Node mergedListHead = new Node();
    Node currentMerged = mergedListHead;
   
    while(currentA != null || currentB != null){
        if(currentA != null && currentB != null){
             if(currentA.data < currentB.data){
                currentMerged.next = currentA;
                currentA = currentA.next;
             }else{
                currentMerged.next = currentB;
                currentB = currentB.next;
             }
        }else if(currentB == null){
            currentMerged.next = currentA;
            break;
        }else if(currentA == null){
            currentMerged.next = currentB;
            break;
        }
        currentMerged = currentMerged.next;
    }
   
   return mergedListHead.next;

}