#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;
}
【C++代码】之《优先队列》
最新推荐文章于 2024-10-08 14:45:27 发布