LeetCode21.合并两个有序链表 python3

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Victordas/article/details/82943817

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

示例:

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

思路:
新手上来第一印象想到的肯定是把链表连上再排序,totally OK,没问题,但是时间复杂度无疑会很高。于是第二种想法,我们不如来增加空间复杂度,创建一个新的链表,按顺序将L1,L2续上。如下:

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

class Solution:
    def mergeTwoLists(self, l1, l2):
        head = ListNode(0)
        New_list = head
        while l1 != None and l2 != None:
            if l1.val > l2.val:
                head.next = l2
                l2 = l2.next
            else:
                head.next = l1
                l1 = l1.next
            head = head.next
            
        if l2 != None:
            head.next = l2
        elif l1 != None:
            head.next = l1
        return New_list.next  
        #New_list一直指着头部,头部是我们指定的0,所以要从下一个开始return
        

猜你喜欢

转载自blog.csdn.net/Victordas/article/details/82943817
今日推荐