用虚拟头节点,在处理的时候会方便许多
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1:
return list2
head = pre = ListNode(val=0,next=list1)
cur1 = list1
cur2 = list2
while cur1 and cur2:
if cur1.val <= cur2.val:
pre.next = cur1
cur1 = cur1.next
else:
pre.next = cur2
cur2 = cur2.next
pre = pre.next
if cur1:
pre.next = cur1
else:
pre.next = cur2
return head.next