链表排序所用到的语言和方法:
1、语言:Python
2、时间复杂度O(nlogn)
3、空间复杂度为常数
4、用的排序算法:二路归并排序
具体实现算法如下所示:
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def sortList(head):
if head == None or head.next == None:
return head
pre = None
slow = head
fast = head
while fast != None and fast.next != None:
pre = slow
slow = slow.next
fast = fast.next.next
pre.next = None
left = sortList(head)
right = sortList(slow)
return merge(left,right)
def merge(left,right):
res = ListNode(0)
temp = res
while left != None and right != None:
if left.val <= right.val:
temp.next = left
temp = temp.next
left = left.next
else:
temp.next = right
temp = temp.next
right = right.next
if left != None:
temp.next = left
if right != None:
temp.next = right
return res.next