# 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
if not list2:
return list1
dummyNode = ListNode(0)
cur = dummyNode
p = list1
q = list2
while p and q:
if p.val <= q.val:
cur.next = p
p = p.next
cur = cur.next
else:
cur.next = q
q = q.next
cur = cur.next
if p:
cur.next = p
if q:
cur.next = q
return dummyNode.next
leetcode 21 合并两个有序链表
最新推荐文章于 2024-06-14 09:50:01 发布