【LeetCode with Python】 Sort List

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/sort-list/
题目类型:
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/38143633

Sort a linked list in O(n log n) time using constant space complexity.


class Solution:

    def findMiddle(self, head):
        slow = head
        fast = head.next
        while None != fast and None != fast.next:
            fast = fast.next.next
            slow = slow.next
        return slow

    def mergeList(self, head):
        if None == head.next:
            return head
        mid = self.findMiddle(head)
        right_head = mid.next
        mid.next = None
        left_list = self.mergeList(head)
        right_list = self.mergeList(right_head)
        new_head = ListNode(-1)
        new_tail = new_head
        left_node = left_list
        right_node = right_list
        while None != left_node and None != right_node:
            if left_node.val <= right_node.val:
                new_tail.next = left_node
                left_node = left_node.next
            else:
                new_tail.next = right_node
                right_node = right_node.next
            new_tail = new_tail.next
        new_tail.next = left_node if None != left_node else right_node
        return new_head.next

    # @param head, a ListNode
    # @return a ListNode
    def sortList(self, head):
        if None == head:            # leetcode will input this !
            return None
        return self.mergeList(head)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值