用python实现优先队列

class priority_queue:
    def __init__(self):
        self.queue = []

    def put(self, val):
        self.queue.append(val)
        cur = len(self.queue) - 1
        while cur > 0:
            parent = (cur - 1) // 2
            if self.queue[parent] > self.queue[cur]:
                self.queue[cur], self.queue[parent] = self.queue[parent], self.queue[cur]
            else:
                break
            cur = parent

    def get(self):
        first = self.top()
        last = self.queue.pop()
        if not self.empty():
            self.queue[0] = last
            cur = 0
            while cur < len(self.queue):
                left_child = 2 * cur + 1
                right_child = 2 * cur + 2
                # 越界
                if right_child >= len(self.queue) or left_child >= len(self.queue):
                    break
                # 无需向下调整
                if self.queue[cur] <= min(self.queue[left_child], self.queue[right_child]):
                    break
                # 与哪个结点交换
                if self.queue[left_child] < self.queue[right_child]:
                    self.queue[left_child], self.queue[cur] = self.queue[cur], self.queue[left_child]
                    cur = left_child
                else:
                    self.queue[right_child], self.queue[cur] = self.queue[cur], self.queue[right_child]
                    cur = right_child
        return first

    def top(self):
        if self.empty():
            raise Exception('the queue is empty!')
        return self.queue[0]

    def find(self, val):
        return val in self.queue

    def get_index(self, index):
        if index >= len(self.queue):
            raise Exception('the index is out of the range!')
        return self.queue[index]

    def empty(self):
        return len(self.queue) == 0

发布了11 篇原创文章 · 获赞 17 · 访问量 3112

猜你喜欢

转载自blog.csdn.net/weixin_43208423/article/details/105245545