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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章