1. 程式人生 > >排序鏈表

排序鏈表

IT fin not 方便 script col nbsp str amp

中英題面

  在 O(n log n) 時間復雜度和常數級空間復雜度下,對鏈表進行排序。

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

  示例 1:

  輸入: 4->2->1->3
  輸出: 1->2->3->4

  Example 1:

  Input: 4->2->1->3
  Output: 1->2->3->4

  示例 2:

  輸入: -1->5->3->4->0
  輸出: -1->0->3->4->5

  Example 2:

  Input: -1->5->3->4->0
  Output: -1->0->3->4->5  



算法

  直接套用歸並排序的思想,為了方便與節省空間,犧牲了一些常數時間。
  時間復雜度:
    O(NlogN)
  空間復雜度:
    O(1)

代碼
 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
5 # self.next = None 6 7 class Solution: 8 def sortList(self, head): 9 """ 10 :type head: ListNode 11 :rtype: ListNode 12 """ 13 if (not head): 14 return None 15 if (not head.next): 16 return head 17 hen = tai = tail = head
18 while (tai.next): 19 tai = tai.next 20 if (tai.next): 21 tail = tail.next 22 else: 23 break 24 tai = tai.next 25 self.adjust(head, tai) 26 hen = tail.next 27 tail.next = None 28 self.adjust(head, tail) 29 self.adjust(hen, tai) 30 self.sortList(head) 31 self.sortList(hen) 32 i = head 33 while (hen): 34 if (i.next): 35 if (i.next.val > hen.val): 36 hen.next, i.next, hen = i.next, hen, hen.next 37 i = i.next 38 else: 39 i.next = hen 40 break 41 return head 42 43 def adjust(self, head, tail): 44 i = head 45 while (i.next): 46 if (head.val > i.next.val): 47 head.val, i.next.val = i.next.val, head.val 48 if (tail.val < i.next.val): 49 tail.val, i.next.val = i.next.val, tail.val 50 i = i.next

排序鏈表