跳到主要内容

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.

分析

代码

# Merge Two Sorted Lists
# Time complexity O(min(m,n)), Space complexity O(1)
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(-1)
p = dummy
while l1 or l2:
val1 = float('inf') if not l1 else l1.val
val2 = float('inf') if not l2 else l2.val
if val1 <= val2:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
return dummy.next

相关题目