Leetcode-Merge Two Sorted Lists(Python)

1 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

2 Solution(解決方案)

解決的思路就是創建一個虛擬的頭節點,形成新列表的表頭,其他的操作就是正常鏈表操作,比較然後指針移動,最後將兩條鏈表中剩餘的全部加入到新鏈中,最後返回虛擬頭結點的next,即爲所求。

def mergeTwoLists(l1, l2) :
        dummy_node = cur = ListNode(1)
        while l1 and l2:
            if l1.val > l2.val: l1, l2 = l2, l1
            cur.next, l1, cur = l1, l1.next, l1
        cur.next = l1 or l2
        return dummy_node.next
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章