You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = [] Output: []
Example 3:
Input: list1 = [], list2 = [0] Output: [0]
Constraints:
- The number of nodes in both lists is in the range
[0, 50]
. -100 <= Node.val <= 100
- Both
list1
andlist2
are sorted in non-decreasing order.
合并两个有序链表。
给两个有序链表,请将两个链表 merge,并且输出的链表也是有序的。
思路很简单,就是用一个 dummy node 去遍历两个链表,然后比较两者的 node.val。直接上代码。
时间O(m + n),两个链表的长度
空间O(1)
这题的 followup 会是 merge K 个链表,参见23题。影子题148,做法几乎一模一样。
Java实现
1 class Solution { 2 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 3 ListNode dummy = new ListNode(0); 4 ListNode cur = dummy; 5 while (l1 != null && l2 != null) { 6 if (l1.val < l2.val) { 7 cur.next = l1; 8 l1 = l1.next; 9 } else { 10 cur.next = l2; 11 l2 = l2.next; 12 } 13 cur = cur.next; 14 } 15 if (l1 != null) { 16 cur.next = l1; 17 } 18 if (l2 != null) { 19 cur.next = l2; 20 } 21 return dummy.next; 22 } 23 }
JavaScript实现
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 };
相关题目
1634. Add Two Polynomials Represented as Linked Lists