请注意!!!!主要用来自己马克自己的笔记,不是最优解!!不是最优解!!不是最优解!!请不要喷我。。。
关键点:题目要求在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
思路:O(nlogn) -> 快排、归并
于是决定:使用归并排序算法对链表进行排序。顺便复习下各类排序算法的时间、空间复杂度。
算法关键点:如何取到middle -> 快慢指针,fast每次走两步,slow每次走一步,fast走到None的时候slow正好是middle。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def merge_sort(head):
if head.next==None:
return head
phead = head
pslow = head
pfast = head
pre = head
while pfast!=None and pfast.next!=None:
pre = pslow
pslow = pslow.next
pfast = pfast.next.next
#pslow此时是middle
pre.next = None
link1 = merge_sort(phead)
link2 = merge_sort(pslow)
return merge(link1,link2)
def merge(left,right):
phead = ListNode(0)
p = phead
while left!=None and right!=None:
if left.val<=right.val:
p.next = left
left = left.next
else:
p.next = right
right = right.next
p = p.next
while left!=None:
p.next = left
left = left.next
p = p.next
while right!=None:
p.next = right
right = right.next
p = p.next
return phead.next
if head==None or head.next==None:
return head
return merge_sort(head)