python-leetcode-合并两个有序链表

21. 合并两个有序链表 - 力扣(LeetCode)

python-leetcode-合并两个有序链表_第1张图片

python-leetcode-合并两个有序链表_第2张图片

python-leetcode-合并两个有序链表_第3张图片

# 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]:
        dummy = ListNode()  # 哑节点
        current = dummy

        while list1 and list2:
            if list1.val < list2.val:
                current.next = list1
                list1 = list1.next
            else:
                current.next = list2
                list2 = list2.next
            current = current.next

        # 将剩余节点链接到结果链表
        current.next = list1 if list1 else list2

        return dummy.next  # 返回合并后链表的头节点

你可能感兴趣的:(leetcode,链表,算法)