1. 程式人生 > >leetcode21題 題解 翻譯 C語言版 Python版

leetcode21題 題解 翻譯 C語言版 Python版

21. Merge Two Sorted Lists

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.

21.合併兩個有序連結串列

合併兩個有序連結串列並將其作為一個新連結串列返回。新連結串列應當由原來的兩個連結串列的結點拼接而成。

思路:兩個連結串列上分別設立遊標來遍歷,同時設立一個表示合併後連結串列的遊標,不停地判斷當前兩連結串列的結點值,取小的結點將其拼接在合併後的連結串列上。由於連結串列都沒有頭結點,所以最開始要單獨判斷一下來獲取最後合併連結串列的頭結點。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    if (!l1 && !l2) return NULL;
    if (!l1) return l2;
    if (!l2) return l1;
    struct ListNode *head, *p;
    if (l1->val < l2->val){
        head = p = l1;
        l1 = l1->next;
    }
    else {
        head = p = l2;
        l2 = l2->next;
    }
    while (l1 && 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 = l2;
    }
    if (!l2){
        p->next = l1;
    }
    return head;
}


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not (l1 or l2): return None
        if not l1: return l2
        if not l2: return l1
        head, p = None, None
        if (l1.val < l2.val):
            head, p = l1, l1
            l1 = l1.next
        else:
            head, p = l2, l2
            l2 = l2.next
        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 not l1:
            p.next = l2
        if not l2:
            p.next = l1
        return head