描述
在 O(n log n) 时间复杂度和常数级的空间复杂度下给链表排序。
您在真实的面试中是否遇到过这个题?
样例
给出 1->3->2->null
,给它排序变成 1->2->3->null
.
挑战
分别用归并排序和快速排序做一遍。
这一题很明显用归并排序或者快速排序来做,但是这一题用归并排序来做有一个好处,在归并的时候不需要移动数组元素了,直接改一个指针就行,因此推荐归并排序。
归并排序算法是必须掌握而且必须能手写出来的,我就不讲解这个算法了。当然此处因为是对链表的操作有一些不同难一些:
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 sortList(self, head):
# write your code here
if(head==None):return None
def findmid(head):
count=0
save=head
while(head!=None):
head=head.next
count+=1
i=0
while(True):
i+=1
if(i>=count/2):break
save = save.next
return save
def merge(left,right):
pre=ListNode(None)
save=pre
while(left!=None and right!=None):
if(left.val<right.val):
pre.next=left
pre=left
left=left.next
else:
pre.next=right
pre=right
right=right.next
if(left==None):
while(right!=None):
pre.next = right
pre = right
right = right.next
if(right==None):
while(left!=None):
pre.next = left
pre = left
left = left.next
return save.next
def mergeSort(head):
if (head.next == None): return head
mid = findmid(head)
midn = mid.next
mid.next = None
left = mergeSort(head)
right = mergeSort(midn)
result = merge(left, right)
return result
result=mergeSort(head)
return result
node1 = ListNode(4)
node2 = ListNode(3)
node3=ListNode(2)
node4 = ListNode(1)
node1.next = node2
node2.next=node3
node3.next=node4
s = Solution()
result = s.sortList(node1)
while (result != None):
print(result.val)
result = result.next