[LeetCode] 21. Merge Two Sorted Lists

混合插入有序链表。给两个有序链表,请将两个链表merge,并且输出的链表也是有序的。思路很简单,就是遍历两个链表,然后比较两者的node。直接上代码。

时间O(m + n),两个链表的长度

空间O(1)

 1 /**
 2  * @param {ListNode} l1
 3  * @param {ListNode} l2
 4  * @return {ListNode}
 5  */
 6 var mergeTwoLists = function(l1, l2) {
 7     let dummy = new ListNode(0);
 8     let cur = dummy;
 9     while (l1 !== null && l2 !== null) {
10         if (l1.val < l2.val) {
11             cur.next = l1;
12             l1 = l1.next;
13         } else {
14             cur.next = l2;
15             l2 = l2.next;
16         }
17         cur = cur.next;
18     }
19     if (l1 !== null) {
20         cur.next = l1;
21     }
22     if (l2 !== null) {
23         cur.next = l2;
24     }
25     return dummy.next;
26 };

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/11828849.html