def qucik_sort_list(head): 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
def reverse(p): newHead = ListNode('') while p: q = p p = p.next q.next = newHead.next newHead.next = q return newHead.next
def mergesort_List(head: ListNode) -> ListNode: def merge(head, q, qk, k): left = right = k while left and right and qk: if q.val > qk.val: head.next = qk qk = qk.next right -= 1 else: head.next = q q = q.next left -= 1 head = head.next head.next = None while left and q: head.next = q q = q.next head = head.next left -= 1 while right and qk: head.next = qk qk = qk.next right -= 1 head = head.next head.next = qk return head k, length = 1, 0 p = head while p: length += 1 p = p.next newHead = ListNode('') newHead.next = head while k < length: head = newHead while head.next: q = qk = head.next for i in range(k): if not qk: break qk = qk.next head = merge(head, q, qk, k) k *= 2 return newHead.next