将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0) # 返回head next
tail = head
while l1 or l2:
if l1 and l2:
if l1.val >=l2.val:
tail.next = ListNode(l2.val)
tail = tail.next
l2 = l2.next
else:
tail.next = ListNode(l1.val)
tail = tail.next
l1 = l1.next
else:
tail.next = l1 if l2 is None else l2
break
return head.next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0) # 返回head next
tail = head
while l1 or l2:
if l1 and l2:
cmp = l1.val >=l2.val
tail.next = ListNode(l2.val) if cmp else ListNode(l1.val)
tail = tail.next
if cmp:
l2 = l2.next
else:
l1 = l1.next
else:
tail.next = l1 if l2 is None else l2
break
return head.next