题目描述
在 O(n log n) 时间复杂度和常数级的空间复杂度下给链表排序。
样例
给出 1->3->2->null,给它排序变成 1->2->3->null.
思路
- 归并法:找到链表的中点分治排序再归并。
- 快排法:把头节点当做基准,分治为小于基准的链表,等于基准的链表和大于基准的链表。最后连起来。
代码
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: The head of linked list.
@return: You should return the head of the sorted linked list, using constant space complexity.
"""
# 归并法
def sortList1(self, head):
# write your code here
if head is None or head.next is None:
return head
pre = head
slow = head
fast = head
while fast is not None and fast.next is not None:
pre = slow
slow = slow.next
fast = fast.next.next
pre.next = None
return self.merge(self.sortList(head), self.sortList(slow))
def merge(self, l1, l2):
if l1 is None:
return l2
if l2 is None:
return l1
if l1.val <= l2.val:
l1.next = self.merge(l1.next, l2)
return l1
else:
l2.next = self.merge(l1, l2.next)
return l2
# 快排法
def sortList2(self, head):
# write your code here
if head is None or head.next is None:
return head
pivot = head
p = pivot
l1 = ListNode(0)
l2 = ListNode(0)
s = l1
f = l2
tmp = head.next
while tmp is not None:
if tmp.val < pivot.val:
s.next = tmp
s = s.next
elif tmp.val == pivot.val:
p.next = tmp
p = p.next
else:
f.next = tmp
f = f.next
tmp = tmp.next
s.next = None
f.next = None
p.next = None
l3 = self.sortList(l1.next)
l4 = self.sortList(l2.next)
if l3 is not None:
l5 = l3
while l5.next is not None:
l5 = l5.next
l5.next = pivot
p.next = l4
return l3
else:
p.next = l4
return pivot
复杂度分析
时间复杂度 O(nlogn) ,空间复杂度 O(1) 。