21. Merge Two Sorted Lists

Description:

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

My code:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
    let min = 0;
    let newList = new ListNode(0);
    let head = newList;
    while(l1 && l2) {
        if(l1.val < l2.val) {
            min = l1.val;
            l1 = l1.next;
        } else {
            min = l2.val;
            l2 = l2.next;
        }
        let temp = new ListNode(min);
        head.next = temp;
        head = head.next;
    }
    head.next = l1? l1: l2;
    return newList.next;
};

Note: 原本是用一个min = 0去与l1跟l2比较的,然后发现思路不对,直接让l1.val跟l2.val比较,较小的直接给head.next就可以了……
P.S. 这提submit以后pending好久,不知道是都这样还是只有我会,第一次见到pending那么久的,还以为超时了……

你可能感兴趣的:(21. Merge Two Sorted Lists)