当前位置: 代码迷 >> 综合 >> Leetcode-Merge Two Sorted Lists(Python)
  详细解决方案

Leetcode-Merge Two Sorted Lists(Python)

热度:71   发布时间:2023-12-03 11:45:49.0

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, l1cur.next, l1, cur = l1, l1.next, l1cur.next = l1 or l2return dummy_node.next