Leet code刷題筆記

Merge Two Sorted Lists -Python解題

困難度:Easy

題目: 簡單來說呢!就是將兩個列表合併為一個排序列表。

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Example 1:

image

Input: list1 = [1,2,4], list2 = [1,3,4]

Output: [1,1,2,3,4,4]

Example 2:

Input: list1 = [], list2 = []

Output: []

Example 3:

Input: list1 = [], list2 = [0]

Output: [0]

Python解題筆記

Inline code has back-ticks around it.

# 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, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        def findMin(n1,n2):
            if n1 == None :
                return n2
            if n2 == None :
                return n1
            if n1.val < n2.val :
                n1.next = findMin(n1.next , n2)
                return n1
            else:
                n2.next = findMin(n1,n2.next)
                return n2
        return findMin(l1,l2)

題目原處-LeetCode