用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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值