(python刷题)leetcode 第21题:合并两个有序链表

题目在leetcode上的链接为:
https://leetcode-cn.com/problems/merge-two-sorted-lists/

题目描述
在这里插入图片描述
解题思路
使用归并排序的合并有序数组的思路即可。

复杂度分析:
需要遍历两个链表,时间复杂度为 o(m+n)
只需要创建常数个指针变量,空间复杂度为 o(1)

python代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1 is None:
            return l2
        if l2 is None:
            return l1
        newhead = p = ListNode(-1)
        while l1 is not None and l2 is not None:
            if l1.val <= l2.val:
                p.next = l1
                l1 = l1.next
            else:
                p.next = l2
                l2 = l2.next
            p = p.next

        p.next = l1 if l1 is not None else l2

        return newhead.next
发布了37 篇原创文章 · 获赞 6 · 访问量 5367

猜你喜欢

转载自blog.csdn.net/qq_37891889/article/details/104372582