[LeetCode] 21. Merge Two Sorted Lists

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 and list2 are sorted in non-decreasing order.

合并两个有序链表。

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

思路是用一个 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 };

 

相关题目

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

LeetCode 题目总结

posted @ 2019-11-10 08:01  CNoodle  阅读(608)  评论(0编辑  收藏  举报