スタックが大きいルート値であることを特徴とノードごとに、その子ノード以上です。
大きなルートヒープは、大きなツリーのルートの両方が完全2分木です。
:例えば図のように
大きなルートヒープデータメンバヒープアレイにarrayLength(ヒープアレイの容量)(一次元配列Tの種類)は、HEAPSIZE(スタック内の要素の数)
以下は、大きなルートの挿入機能のスタックです。
//插入函数
template<class T>
void maxHeap<T>::push(const T& theElement)
{
//若数组长度不够
if(heapSize==arrayLength-1)
{
changeLength1D(heap,arrayLength,2*arrayLength);
arrayLength*=2;
}
int currentNode=++heapSize;
while(currentNode!=1&&heap[currentNode/2]<theElement)
{
heap[currentNode]=heap[currentNode/2];
currentNode/=2;
}
heap[currentNode]=theElement;
}
削除機能:
//删除函数
template<class T>
void maxHeap<T>::pop()
{
if(heapSize==0)
throw queueEmpty();//若堆为空
//删除最大元素
heap[1].~T();
//删除最后一个元素,重新建堆
T lastElement=heap[heapSize--];
//从根开始,为最后一个元素寻找元素
int currentNode=1,child=2;
while(child<=heapSize)
{
if(child<heapSize&&heap[child]<heap[child+1])
child++;
//可以把lastElement放在heap[currentNode]吗?
if(lastElement>=heap[child])
break;
heap[currentNode]=heap[child];//把孩子child向上移动
currentNode=child;//向下移动一层寻找位置
child*=2;
}
heap[currentNode]=lastElement;
}