我需要有关此 minheap 代码的帮助:
#include < vector>
using namespace std;
class heap {
vector <int> v;
public:
int hSize()
{
return v.size();
}
int rsize()
{
return hSize() - 1;
}
int parent(int i)
{
return (i - 1) / 2;
}
int left(int i)
{
return i * 2 + 1;
}
int right(int i)
{
return i * 2 + 2;
}
void swap(int i, int j)
{
int temp = v[j];
v[j] = v[i];
v[i] = temp;
}
void push(int e)
{
v.push_back(e);
int id = rsize();
if (hSize() > 1)
while (v[parent(id)] > v[id]) {
swap(parent(id), id);
id = parent(id);
}
}
int pop ()
{
int f = 0;
int p = v[0];
v[0] = v[rsize()];
if (hSize() > 1) {
while (v[left(f)] < v[f] || v[right(f)] < v[f]) {
if (v[left(f)] < v[f] && v[right(f)] < v[f]) {
if (v[left(f)] < v[right(f)]) {
swap(left(f), f);
f = left(f);
}
else {
swap(right(f), f);
f = right(f);
}
}
else {
if (v[left(f)] < v[f]){
swap(left(f), f);
f = left(f);
}
else {
swap(right(f), f);
f = right(f);
}
}
}
}
else { }
v.resize(rsize());
return p;
}
void show()
{
if (hSize() > 0) {
cout << "Heap content: ";
for (int i = 0; i < hSize(); i++) cout << v[i] << " ";
}
else cout << "\nHeap successfully emptied!";
cout << "\n";
}
bool Empty()
{
return v.empty();
}
~heap()
{
v.clear();
}
};
好吧,代码几乎做对了所有事情,除了当它弹出屏幕上的最后一个元素时,它会打印一个随机数。你怎么看?
谢谢!