Skip to content

Latest commit

 

History

History
30 lines (30 loc) · 622 Bytes

mergeTwoSortedLists.md

File metadata and controls

30 lines (30 loc) · 622 Bytes
/**
 * 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) {
    var head = new ListNode();
    var pre = head; // 保存头节点
    while(l1 && l2) {
        if (l1.val < l2.val) {
            pre.next = l1;
            l1 = l1.next;
        } else {
            pre.next = l2;
            l2 = l2.next;
        }
        pre = pre.next;
    }
    pre.next = l1 ? l1 : l2; // 合并剩余链表
    return head.next
};