【Leetcode链表】合并两个有序链表(21)

题目

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

输入:1->2->4, 5
输出:1->2->4->5

题解

三种方法:

  • 尾插法,更改原始链表。时间复杂度O(n),空间复杂度O(1)
  • 原链表不变,另开辟新空间。时间复杂度O(n+m),空间复杂度O(n+m)
  • 递归,没懂。。。

通过代码如下:

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

class Solution:
    # 方法一:
    # 尾插法,更改原始链表。时间复杂度O(n),空间复杂度O(1)
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        thead = ListNode(-1)  # 开辟一个表头结点,用于返回时候使用
        t = thead
        while l1 and l2:
            if l1.val<=l2.val:
                t.next = l1
                t = l1
                
                l1 = l1.next
            else:
                t.next = l2
                t = l2

                l2 = l2.next
        # 以下是把没走完的链表添加到尾部
        if l1:
            t.next = l1
        if l2:
            t.next = l2
        return thead.next


    # # 方法二:
    # # 原链表不变,另开辟新空间。时间复杂度O(n+m),空间复杂度O(n+m)
    # def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
    #     head = ListNode(0)
    #     temp = head
    #     c2 = l2
    #     while l1 and c2:
    #         if l1.val <= c2.val:
    #             t = ListNode(l1.val)
    #             temp.next = t
    #             temp = t
                
    #             l1 = l1.next            
    #         else:
    #             t = ListNode(c2.val)
    #             temp.next = t
    #             temp = t

    #             c2 = c2.next
    #     while l1:
    #         temp.next = l1
    #         temp = l1
    #         l1 = l1.next
    #     while c2:
    #         temp.next = c2
    #         temp = c2
    #         c2 = c2.next
    #     return head.next


    # # 方法三:递归,这个答案是抄的,没懂。。。
    # def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
    #     # 若有一个为空,则直接返回另一个
    #     if not l1:
    #         return l2
    #     if not l2:
    #         return l1
    #     # 递归可以理解为之后的情况都处理好了,只需要解决好当前这步就行了
    #     if l1.val <= l2.val:
    #         l1.next = self.mergeTwoLists(l1.next, l2)
    #         return l1
    #     else:
    #         l2.next = self.mergeTwoLists(l1, l2.next)
    #         return l2

猜你喜欢

转载自www.cnblogs.com/ldy-miss/p/11935619.html