Sort a linked list in O(n log n) time using constant space complexity.
这道题要求时间为nlogn我们联想到quick sort 或者mergesort这里采用mergesort
quick sort的最差为n^2 在逆序的时候。
和array mergesort不同的是这里找Mid 需要用两个pointer一个fast 一个slow
当fast.走到底的时候slow 刚刚好走到中间 其他的做法与array的mergesort一样。
代码如下
class ListNode:
def __init__(self,val):
self.val=val
self.next=None
head=root=ListNode(0)
head.next=ListNode(10)
head=head.next
head.next=ListNode(22)
head=head.next
head.next=ListNode(3)
head=head.next
head.next=ListNode(1)
head=head.next
head.next=ListNode(2)
head=head.next
head.next=ListNode(4)
def printL(root):
while root:
print root.val
root=root.next
printL(root)
def merge(left,right):
dummy=ListNode(0)
newhead=dummy
if left==None:
return right
if right==None:
return left
while left and right:
if left.val<right.val:
newhead.next=ListNode(left.val)
left=left.next
else:
newhead.next=ListNode(right.val)
right=right.next
newhead=newhead.next
if left:
newhead.next=left
if right:
newhead.next=right
return dummy.next
newhead=merge(root,root)
printL(newhead)
def mergesort(root):
if root.next==None or root==None:
return root
fast=root
slow=root
while fast.next and fast.next.next:
fast=fast.next.next
slow=slow.next
left=root
right=slow.next
slow.next=None
left=mergesort(left)
right=mergesort(right)
return merge(left,right)
newhead=mergesort(root)
printL(newhead)