原题:
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head):
h, length, intv = head, 0, 1
while h:
h, length = h.next, length + 1
res = ListNode(0) # 创建辅助链表,存储排序的链节点
res.next = head
# 不断的合并链节点
while intv < length:
pre, h = res, res.next
while h:
# 得到两个合并的节点h1,h2
h1, i = h, intv
while i and h:
h, i = h.next, i - 1
if i:
break # 如果i不为0,则说明h1链的节点数不足intv个,那么h2 is None
h2, i = h, intv
while i and h:
h, i = h.next, i - 1
c1, c2 = intv, intv - i # h2的长度可能没有intv,所以由intv-i得
# 合并h1和h2
while c1 and c2:
if h1.val < h2.val:
pre.next, h1, c1 = h1, h1.next, c1 - 1
else:
pre.next, h2, c2 = h2, h2.next, c2 - 1
pre = pre.next
# 之后c1或c2必有一个为0.
pre.next = h1 if c1 else h2
while c1 > 0 or c2 > 0:
pre, c1, c2 = pre.next, c1 - 1, c2 - 1
pre.next = h #连接下一部分的intv
intv *= 2
return res.next