[Lintcode]98. Sort List/[Leetcode]148. Sort List

98. Sort List/148. Sort List

  • 本题难度: Medium
  • Topic: Linked List

Description

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

Example
Example 1:
Input: 1->3->2->null
Output: 1->2->3->null

Example 2:
Input: 1->7->2->6->null
Output: 1->2->6->7->null

Challenge
Solve it by merge sort & quick sort separately.

Challenge
Can you do this in-place without altering the nodes' values?

我的代码

class Solution(object):
    def merge(self,x,y):
        pos = ListNode(0)
        res = pos
        while(x and y):
            if x.val<y.val:
                pos.next = x
                x = x.next
            else:
                pos.next = y
                y = y.next
            pos = pos.next
        pos.next = x or y
        return res.next
        
        
    def sortList(self,head):
        if not head or not head.next:
            return head
        
        pre,slow,fast = None, head,head
        while fast and fast.next:
            pre,slow,fast = slow,slow.next,fast.next.next
        pre.next = None# 保证第一列始终不长于第二列
        
        return self.merge(*map(self.sortList,(head,slow)))

思路
采用归并排序

  • 时间复杂度 O(nlog(n))

猜你喜欢

转载自www.cnblogs.com/siriusli/p/10376473.html