LeetCode-merge two sorted linked lists (JS implementation)

Title description

Problem-solving ideas

  • Create a new linked list node newNode
  • Specify a temporary pointer h to point to this new node newNode
  • Use a while loop to traverse under the condition that both L1 and L2 are not empty. If the value of the current data field of L1 is small, let newNode point to L1, otherwise point to L2
  • After the while loop is traversed, if either of L1 or L2 has surplus, whoever is added to the end of newNode.
  • The last returned is the next field of the h temporary pointer, because the h temporary pointer just started pointing to our newly created node.

Implementation code

var mergeTwoLists = function(l1, l2) {
    
    
    // 首先创建一个新的节点
    let newNode = new ListNode();
    const h = newNode;
    // 循环遍历两个列表
    while (l1 && l2) {
    
    
        if (l1.val < l2.val) {
    
    
            newNode.next = l1;
            l1 = l1.next;
            newNode = newNode.next;
        } else {
    
    
            newNode.next = l2;
            l2 = l2.next;
            newNode = newNode.next;
        }
    } 
    if (l1) newNode.next = l1;
    if (l2) newNode.next = l2;
    return h.next;
};

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/115166356