【力扣100】21.合并两个有序链表

添加链接描述

# 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
        
        if list1.val<=list2.val:
            list1.next=self.mergeTwoLists(list1.next,list2)
            return list1
        else:
            list2.next=self.mergeTwoLists(list1,list2.next)
            return list2

思路:

  1. 递归,合并同类

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