难度:Medium ?:1634
题目
对链表进行排序,要求:
O(n log n) 时间复杂度;常数级空间复杂度
思路
采取归并排序法。
解答
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def merge_list(self,head1,head2):
if head1 == None or head2 == None:
return head1 or head2
head0 = ListNode(-1)
tmp = head0
while head1 and head2:
if head1.val < head2.val:
tmp.next = head1
head1 = head1.next
else:
tmp.next = head2
head2 = head2.next
tmp = tmp.next
tmp.next = head1 or head2
return head0.next
def sortList(self, head: ListNode) -> ListNode:
slow = head
fast = head
if head == None or head.next == None:
return head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
tmp = slow.next
print(tmp.val)
slow.next = None
return self.merge_list(self.sortList(head),self.sortList(tmp))
注意:在寻找链表的中点时,我一开始犯了个错误。情形简化如下:
1 -> 2
while fast and fast.next:
slow = slow.next
fast = fast.next.next
这就导致,最后slow停在2,左半边仍然是1 -> 2,无限循环。