题目描述
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序
示例1
输入: 4->2->1->3
输出: 1->2->3->4
示例2
输入: -1->5->3->4->0
输出: -1->0->3->4->5
解题思路
归并排序
总的思路就是把链表断为等长的链表,从较短的链表开始排序,然后将排序后的链表继续排序,直到整个链表排序完成,具体步骤以示例2为例:
step1:(-1->5)->(3->4)->(0)
step2:(-1->3->4->5)->(0)
step3:-1->0->3->4->5
代码实现
实现归并排序,需要实现两个子过程:
cut(node,n)
:将以node
为开头的链表断为固定长度为n
的子链,返回被断链表在断链之后剩下链表的表头merge(l1,l2)
:将两条链表按照从小到大顺序归并成一条链表,并返回链表表头
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head: ListNode) -> ListNode:
node = ListNode(0)
length = 0
node.next = head
while head != None:
head = head.next
length += 1
j = 1
while j<length:
cur = node.next
tail = node
while cur!=None:
left = cur
right = self.cut(cur,j)
cur = self.cut(right,j)
tail.next = self.merge(left,right)
while tail.next!=None:
tail = tail.next
j*=2
return node.next
def cut(self,cur: ListNode,n: int) -> ListNode:
p = cur
while p!=None and n > 1:
p = p.next
n -= 1
if p == None:
return None
q = p.next
p.next = None
return q
def merge(self,left: ListNode, right: ListNode)->ListNode:
p = ListNode(0)
node = p
while left!=None and right!=None:
if left.val <= right.val:
node.next = left
node = node.next
left = left.next
else:
node.next = right
node = node.next
right = right.next
if right != None:
node.next = right
if left!=None:
node.next = left
return p.next
复杂度分析
时间复杂度为 O ( n log n ) O(n\log n) O(nlogn),空间复杂度为 O ( 1 ) O(1) O(1)