1. 程式人生 > >LeetCode(21. 合並兩個有序鏈表)

LeetCode(21. 合並兩個有序鏈表)

最小 __init__ 有序鏈表 get 方案 leet 代碼 return odin

問題描述

將兩個有序鏈表合並為一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。

示例:

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

解決方案

# encoding: utf-8

class Node(object):
    def __init__(self):
        self.val = None
        self.next = None

    def __str__(self):
        return str(self.val)


def mergeTwoLists(l1, l2):
    # 處理邊界情況(l1或l2為空)
    if l1 is None:
        return l2
    if l2 is None:
        return l1
    # 確保l1有最小的初始值
    if l2.val < l1.val:
        l1, l2 = l2, l1
    # 保存一個鏈表頭用來作為返回值
    head = l1
    # 開始叠代到l1為最後一個節點
    while l1.next is not None:
        # 假如l2完結,工作完成
        if l2 is None:
            return head
        # 假如l2節點屬於在l1的當前節點與下一個節點值之間
        if l1.val <= l2.val <= l1.next.val:
            # 在這一步我們通過設置l1.next\l2.next來拼接l2,並將L2 叠代
            l1.next, l2.next, l2 = l2, l1.next, l2.next
        # l1叠代向前
        l1 = l1.next
    # 以防l2較長的情況,我們在l1叠代完成後把l2加入到l1尾部
    l1.next = l2
    return head

測試代碼

if __name__ == '__main__':

    three = Node()
    three.val = 3

    two = Node()
    two.val = 2
    two.next = three

    one = Node()
    one.val = 1
    one.next = two

    head = Node()
    head.val = 0
    head.next = one

    three1 = Node()
    three1.val = 3

    two1 = Node()
    two1.val = 2
    two1.next = three1

    one1 = Node()
    one1.val = 1
    one1.next = two1

    head1 = Node()
    head1.val = 0
    head1.next = one1
    newhead = mergeTwoLists(head, head1)
    while newhead:
        print(newhead.val, )
        newhead = newhead.next

LeetCode(21. 合並兩個有序鏈表)