21 Merge Two Sorted Lists 合并兩個有序鏈表
Description:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
題目描述:
將兩個有序鏈表合并為一個新的有序鏈表并返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
示例:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
不同于順序表, 鏈表中存儲的為值(val)以及指向下一個結點的指針(*next)
插入的時間復雜度為O(1), 隨機訪問的時間復雜度為O(n)
結構類似于: val(1), next -> val(2), next -> ...
C++定義鏈表:struct ListNode { // 值 int val; // 指向下一個結點的指針 ListNode *next; // 初始化鏈表 ListNode(int x) : val(x), next(NULL) {} };
思路:
- 遞歸. l1的值小于l2的值, l1指向next結點, l2不變.
- 迭代. 結束條件為l1和l2指向空.
時間復雜度O(n + m), 其中n和m分別為兩個鏈表的長度, 空間復雜度O(1)
代碼:
C++:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if (!l1) return l2;
if (!l2) return l1;
if (l1 -> val < l2 -> val)
{
l1 -> next = mergeTwoLists(l1 -> next, l2);
return l1;
}
else
{
l2 -> next = mergeTwoLists(l1, l2 -> next);
return l2;
}
}
};
Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
Python:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
# result/p初始化頭結點
result = p = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
if l1:
p.next = l1
else:
p.next = l2
return result.next