leetcode-148-排序链表*
题目描述:
方法一:快排
class Solution: def sortList(self, head: ListNode) -> ListNode: def partition(start, end): node = start.next.next pivotPrev = start.next pivotPrev.next = end pivotPost = pivotPrev while node != end: temp = node.next if node.val > pivotPrev.val: node.next = pivotPost.next pivotPost.next = node elif node.val < pivotPrev.val: node.next = start.next start.next = node else: node.next = pivotPost.next pivotPost.next = node pivotPost = pivotPost.next node = temp return [pivotPrev, pivotPost] def quicksort(start, end): if start.next != end: prev, post = partition(start, end) quicksort(start, prev) quicksort(post, end) newHead = ListNode(0) newHead.next = head quicksort(newHead, None) return newHead.next
方法二:归并排序
class Solution: def sortList(self, head: ListNode) -> ListNode: if not head or not head.next: return head slow, fast = head, head.next while fast and fast.next: fast, slow = fast.next.next, slow.next mid, slow.next = slow.next, None left, right = self.sortList(head), self.sortList(mid) 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