Constraints: The number of nodes in both lists is in the range [0, 50]. -100 <= Node.val <= 100 Both list1 and list2 are sorted in non-decreasing order.
合并两个有序链表。
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
思路
思路是用一个 dummy node 去遍历两个链表,对于来自两个链表上的 node,谁的 val 小谁就在前。直接上代码。
这题的 followup 会是 merge K 个链表,参见 23 题。影子题 148,做法几乎一模一样。
/** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var mergeTwoLists = function(l1, l2) { let dummy = newListNode(0); let cur = dummy; while (l1 !== null && l2 !== null) { if (l1.val < l2.val) { cur.next = l1; l1 = l1.next; } else { cur.next = l2; l2 = l2.next; } cur = cur.next; } if (l1 !== null) { cur.next = l1; } if (l2 !== null) { cur.next = l2; } return dummy.next; };
相关题目
1 2 3 4 5
21. Merge Two Sorted Lists 23. Merge k Sorted Lists 148. Sort List 1634. Add Two Polynomials Represented as Linked Lists 1940. Longest Common Subsequence Between Sorted Arrays