#include <iostream>
using namespace std;
#include <map>
class heap
{
public:
int heapSize;
int limit;
int* heapArray;
map<int, int> heapMap;
heap(int limit)
{
this->limit = limit;
this->heapArray = new int[limit];
heapSize = 0;
}
void swapMap(int i, int j)
{
heapMap[heapArray[i]] = j;
heapMap[heapArray[j]] = i;
}
void push(int value)
{
if (heapSize == limit)
{
cout << "heap is full";
return;
}
heapArray[heapSize] = value;
this->heapMap.insert(make_pair(value, heapSize));
heapInsert(heapSize++);
}
void heapInsert(int index)
{
while (heapArray[index] > heapArray[(index - 1) / 2])
{
swapMap(index, (index - 1) / 2);
swap(heapArray[index], heapArray[(index - 1) / 2]);
index = (index - 1) / 2;
}
}
void delete_num(int num)
{
int index = heapMap[num];
swapMap(index, heapSize - 1);
swap(heapArray[index], heapArray[heapSize-- - 1]);
heapify(index);
heapInsert(index);
}
int heapPop()
{
if (heapSize < 1)
{
cout << "heap is empty";
return -1;
}
heapMap.erase(heapArray[0]);
int temp = heapArray[0];
swapMap(0, heapSize-1);
swap(heapArray[0], heapArray[heapSize-- - 1]);
heapify(0);
return temp;
}
void heapify(int index)
{
int left= index * 2 + 1;
while (left < heapSize)
{
int largest = left + 1 < heapSize && heapArray[left + 1] > heapArray[left] ? left + 1 : left;
if (heapArray[index] > heapArray[largest])
break;
swapMap(index, largest);
swap(heapArray[index], heapArray[largest]);
index = largest;
left= index * 2 + 1;
}
}
void heapShow()
{
for (int i = 0; i < heapSize; i++)
{
cout << heapArray[i] << ' ';
}
}
};
函数名即为操作方式,也就不做注释了
利用反向索引表记录当前值所在位置,从表中获取当前的值,与末位值交换,进行heapify和heapInsert即可实现系统提供的堆无法实现的删除指定值操作
int main(void)
{
heap a = heap(10);
a.push(10);
a.push(2);
a.push(13);
a.push(999);
a.push(888);
a.delete_num(999);
int i = a.heapPop();
cout << i << endl;
a.heapShow();
cout << a.heapSize;
return 0;
}
输出:
888
13 2 10 3