【C++代码】之《优先队列》

#include <iostream>
#include <stack>
#include <vector>

using namespace std;

// 最大优先队列
class MaxPriorityQueue
{
private:
    vector<int> array;
public:
    MaxPriorityQueue() : array()
    {
        cout << "调用默认构造函数!" << endl;
    };
    MaxPriorityQueue(const MaxPriorityQueue & queue) : array(queue.array)
    {
        cout << "调用拷贝构造函数!" << endl;
    }
    const MaxPriorityQueue & operator=(const MaxPriorityQueue & queue)
    {
        cout << "调用拷贝赋值操作符!" << endl;
        array = queue.array;
        return *this;
    }
    const int size() const
    {
        return array.size();
    }
    void push(const int & num)
    {
        array.push_back(num);
        UpAdjust();
    }
    const int top() const
    {
        if (array.empty())
        {
            return -1;
        }
        else
        {
            return array.front();
        }
    }
    bool empty() const
    {
        return array.empty() ? true : false;
    }
    void UpAdjust()
    {
        int childIndex = array.size() - 1;
        int parentIndex = (childIndex - 1) / 2;
        const int temp = array.back();
        while (childIndex > 0 && temp > array[parentIndex])
        {
            array[childIndex] = array[parentIndex];
            childIndex = parentIndex;
            parentIndex = (childIndex - 1) / 2;
        }
        array[childIndex] = temp;
    }
    void DownAdjust()
    {
        int parentIndex = 0;
        int childIndex = 2 * parentIndex + 1;
        const int temp = array.front();
        while (childIndex < array.size())
        {
            // 找到左右孩子中的最大值
            if (childIndex + 1 < array.size() && array[childIndex + 1] > array[childIndex])
            {
                ++childIndex;
            }
            if (temp >= array[childIndex])
            {
                break;
            }
            else
            {
                array[parentIndex] = array[childIndex];
                parentIndex = childIndex;
                childIndex  = 2 * parentIndex + 1;
            }
        } 
        array[parentIndex] = temp;
    }
    void pop()
    {
        if (array.empty())
        {
            return;
        }
        else
        {
            swap(array.front(), array.back());
            array.pop_back();
            DownAdjust();
        }
    }
};

int main()
{
    MaxPriorityQueue queue;
    queue.push(8);
    queue.push(9);
    queue.push(3);
    queue.push(10);
    while (!queue.empty())
    {
        cout << queue.top() << '\t';
        queue.pop();
    }
    cout << endl;
    MaxPriorityQueue queue1 = queue;
    return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值