LeetCode #21 Merge Two Sorted Lists 合并兩個(gè)有序鏈表

21 Merge Two Sorted Lists 合并兩個(gè)有序鏈表

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

題目描述:
將兩個(gè)有序鏈表合并為一個(gè)新的有序鏈表并返回。新鏈表是通過拼接給定的兩個(gè)鏈表的所有節(jié)點(diǎn)組成的。

示例:

輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4

鏈表 Linked list-wiki:

不同于順序表, 鏈表中存儲(chǔ)的為值(val)以及指向下一個(gè)結(jié)點(diǎn)的指針(*next)
插入的時(shí)間復(fù)雜度為O(1), 隨機(jī)訪問的時(shí)間復(fù)雜度為O(n)
結(jié)構(gòu)類似于: val(1), next -> val(2), next -> ...
C++定義鏈表:

struct ListNode {
    // 值
    int val;
    // 指向下一個(gè)結(jié)點(diǎn)的指針
    ListNode *next;
    // 初始化鏈表
    ListNode(int x) : val(x), next(NULL) {}
};

思路:

  1. 遞歸. l1的值小于l2的值, l1指向next結(jié)點(diǎn), l2不變.
  2. 迭代. 結(jié)束條件為l1和l2指向空.
    時(shí)間復(fù)雜度O(n + m), 其中n和m分別為兩個(gè)鏈表的長度, 空間復(fù)雜度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初始化頭結(jié)點(diǎn)
        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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容