链表快速排序

class Node:
    def __init__(self, x, next=None):
        self.value=x
        self.next=next


def Qsort(head, tail):
    if head==None or tail==None or head==tail:
        return
    first=head
    second=first.next
    key=head.value
    while second!=None:
        if second!=None and second.value>=key:
            second = second.next
        else:
           first=first.next
           first.value, second.value = second.value, first.value
           second = second.next
    first.value, head.value = head.value, first.value
    Qsort(head, first)
    Qsort(first.next, tail)


def printlist(head):
    p=head
    while p:
        print(p.value)
        p=p.next

tail=Node(3,None)
a1=Node(2,tail)
a2=Node(5,a1)
a3=Node(0, a2)
a4=Node(1, a3)
a5=Node(-4, a4)
head=Node(3, a5)
print("排序前:")
printlist(head)
print("排序后:")
Qsort(head, tail)
printlist(head)

猜你喜欢

转载自www.cnblogs.com/tsdblogs/p/9807864.html