HOT 100 › 索引 › B7 链表 Linked List
LC 148排序链表Sort List 中等
将单链表节点值升序排序并返回头节点,要求 O(n log n) 时间。
思路 归并:快慢指针切半,递归排序后合并两条有序链。时间 O(n log n)。
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 = slow.next fast = fast.next.next mid = slow.next slow.next = None left = self.sortList(head) right = self.sortList(mid) return self.merge(left, right) def merge(self, a, b): dummy = cur = ListNode() while a and b: if a.val <= b.val: cur.next = a a = a.next else: cur.next = b b = b.next cur = cur.next cur.next = a if a else b return dummy.next