题目描述:在 O(nlogn) 时间复杂度和常数空间复杂度下对链表进行排序。
其实这道题我并没有完成,使用递归方法空间复杂度 O(logn),但是非递归的归并排序实在是麻烦,就先作罢了。我从题解学到了一个用快慢指针一次遍历找到链表中点的方法,比我以前用的两次法显然好的多,这里记录一下。代码如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head):
if not head or not head.next:
return head
# 使用快慢指针,快指针到达尾部时,慢指针的位置就是链表中点
slow, fast = head, head.next
while fast and fast.next:
slow, fast = slow.next, fast.next.next
mid, slow.next = slow.next, None
left = self.sortList(head)
right = self.sortList(mid)
ans = ListNode(-1)
cur = ans
while left and right:
if left.val < right.val:
cur.next = left
left = left.next
else:
cur.next = right
right = right.next
cur = cur.next
while left:
cur.next = left
left = left.next
cur = cur.next
while right:
cur.next = right
right = right.next
cur = cur.next
return ans.next