力扣148-排序链表
对于nlogn的时间复杂度要求,使用归并,与数组不同的是:
1)链表找中点,通过快慢指针,找到左右的头节点即可,切断链表操作.
2)建立新的伪节点,不断比较left和right的值,进行组合。
3)这里空间复杂度还是有栈的调用,不是常数级别,后续代码太复杂,以后有时间再看
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def sortList(self, head: ListNode) -> ListNode: if not head or not head.next :return head # 1/ 切分链表,奇数节点数在中间,偶数节点数偏左 slow = head fast = head.next while 1: if not fast or not fast.next: break fast = fast.next.next slow = slow.next mid = slow rightNode = mid.next slow.next = None left,right = self.sortList(head),self.sortList(rightNode) # 归并排序 h = res = ListNode(0) while left and right: if left.val<right.val: h.next = left left = left.next else: h.next = right right = right.next h = h.next h.next = left if left else right return res.next