Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
 def reverse(p):
     newHead = ListNode('')
     while p:
         q = p
         p = p.next
         q.next = newHead.next
         newHead.next = q
     return newHead.next
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
 def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
     if l1 and l2:
         if l1.val > l2.val: l1, l2 = l2, l1
         l1.next = mergeTwoLists(l1.next, l2)
     return l1 or l2