排序链表

中英题面

  在 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

猜你喜欢

转载自www.cnblogs.com/Efve/p/9062365.html