Python 双向链表 快速排序

1、创建链表:

from random import randint


class DLinkedNode(object):

    def __init__(self, data=None, pre=None, post=None):
        self.data = data
        self.pre = pre
        self.post = post


class DLinkedList(object):

    def __init__(self):
        self.head = DLinkedNode()
        self.tail = DLinkedNode()
        self.head.post = self.tail
        self.tail.pre = self.head

    def build(self, n):
        pre = self.head
        for _ in range(n):
            data = randint(1, 100)
            node = DLinkedNode(data, post=self.tail)
            self.tail.pre = node
            pre.post = node
            node.pre = pre
            pre = node

        return self.head, self.tail

2、快速排序:

class Solution(object):

    def quick_sort(self, head, low, high):
        if not head or not head.post:
            return

        if low != high:
            p, q = low, high
            key = p.data
            while p != q:
                while p != q and q.data >= key:
                    q = q.pre
                p.data = q.data
                while p != q and p.data <= key:
                    p = p.post
                q.data = p.data
            p.data = key

            if low != p:
                self.quick_sort(head, low, p.pre)
            if p != high:
                self.quick_sort(head, p.post, high)

3、测试:

h, t = DLinkedList().build(10)
curr = h
while curr.post:
    print curr.post.data,
    curr = curr.post
print()
while curr.pre:
    print curr.pre.data,
    curr = curr.pre
print()

Solution().quick_sort(h.post, h.post, t.pre)
curr = h

while curr.post:
    print curr.post.data,
    curr = curr.post

猜你喜欢

转载自www.cnblogs.com/xiaoerlang/p/10513461.html