优先队列(PriorityQueue)

> 此代码是在最大堆的基础上二次封装,请先阅读底层代码MaxHeap

优先队列

  • 普通队列:先进先出;后进后出
  • 优先队列:出队顺序和⼊入队顺序无关;和优先级相关;

为什么使用堆

在这里插入图片描述

代码清单

Queue.h

//
// Created by cheng on 2021/7/11.
//

#ifndef MAXHEAP_QUEUE_H
#define MAXHEAP_QUEUE_H

template<typename T>
class Queue {
public:
    virtual int getSize() = 0;

    virtual bool isEmpty() = 0;

    virtual void enqueue(const T &e) = 0;

    virtual T dequeue() = 0;

    virtual T getFront() = 0;
};

#endif //MAXHEAP_QUEUE_H

PriorityQueue.h

//
// Created by cheng on 2021/7/11.
//

#ifndef MAXHEAP_PRIORITYQUEUE_H
#define MAXHEAP_PRIORITYQUEUE_H

#include "MaxHeap.h"
#include "Queue.h"

template<typename T>
class PriorityQueue : public Queue<T> {

private:
    MaxHeap<T> *maxHeap;

public:
    PriorityQueue() {
        maxHeap = new MaxHeap<T>();
    }

    constexpr int getSize() {
        return maxHeap->getSize();
    }

    constexpr bool isEmpty() {
        return maxHeap->isEmpty();
    }

    void enqueue(const T &e) {
        maxHeap->add(e);
    }

    T dequeue() {
        return maxHeap->extractMax();
    }

    T getFront() {
        return maxHeap->findMax();
    }

    ~PriorityQueue() {
        delete maxHeap;
        maxHeap = nullptr;
    }

    void print() {
        std::cout << "Queue: size = " << maxHeap->getSize() << std::endl;
        std::cout << "front ";
        maxHeap->print();
        std::cout << " tail" << std::endl;
    }
};

#endif //MAXHEAP_PRIORITYQUEUE_H
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吃米饭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值