Leetcode148. 链表排序 (Python3解法)

难度:Medium ?:1634

题目

对链表进行排序,要求:
O(n log n) 时间复杂度;常数级空间复杂度

思路

采取归并排序法。

解答

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

class Solution:
    def merge_list(self,head1,head2):
        if head1 == None or head2 == None:
            return head1 or head2
        head0 = ListNode(-1)
        tmp = head0

        while head1 and head2:
            if head1.val < head2.val:
                tmp.next = head1
                head1 = head1.next
            else:
                tmp.next = head2
                head2 = head2.next
            tmp = tmp.next 
        
        tmp.next = head1 or head2
        return head0.next
    
    def sortList(self, head: ListNode) -> ListNode:
   
        slow = head
        fast = head
        
        if head == None or head.next == None:
            return head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        
        tmp = slow.next
        print(tmp.val)
        slow.next = None
        
        return self.merge_list(self.sortList(head),self.sortList(tmp))

注意:在寻找链表的中点时,我一开始犯了个错误。情形简化如下:
1 -> 2
while fast and fast.next:
slow = slow.next
fast = fast.next.next
这就导致,最后slow停在2,左半边仍然是1 -> 2,无限循环。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值