preloader
Leetcode

Leetcode - Merge Two Sorted List - my solution using javascript

Leetcode - Merge Two Sorted List - my solution using javascript

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

 

Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

 

Example 2:
Input: l1 = [], l2 = []
Output: []

 

Example 3:
Input: l1 = [], l2 = [0]
Output: [0]

 

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both l1 and l2 are sorted in non-decreasing order.

 

My solution using javascript:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
    
    let tmp = new ListNode();
    let tmpHead = tmp;
    tmp.next = new ListNode();
    tmp = tmp.next;

    // handle corner cases including they are empty
    if (l1 === null && l2 === null) {
        return l1;
    } else if (l1 === null) {
        return l2;
    } else if (l2 === null) {
        return l1;
    }
    
    // handle when both l1 and l2 are not empty
    while ( l1 && l2) {
        
        if ( l1.val <= l2.val) {
            tmp.val = l1.val;
            l1 = l1.next;
        } else {
            tmp.val = l2.val;
            l2 = l2.next;
        }
        
        tmp.next = new ListNode();
        tmp = tmp.next; 
    }
    
    // handle rest part of l1 after handling completely both of l1 and l2
    while (l1 != null) {
        tmp.val = l1.val;
        tmp.next = l1.next;
        tmp = tmp.next;
        l1 = l1.next;
    }
    
    // handle rest part of l2 after handling completely both l1 and l2
    while (l2 != null) {
        tmp.val = l2.val;
        tmp.next = l2.next;
        tmp = tmp.next;
        l2 = l2.next;
    }
    
    // return merged result
    return tmpHead.next;
    
};