大顶堆(c++实现)

【大顶堆的性质】

大顶堆是一棵完全二叉树,且树中的每个节点的值都不小于它的孩子节点的值。我们可以用一个heap数组来表示它。

【大顶堆的插入、删除】

  1. 大顶堆的插入:首先初始化插入位置为最后,然后从下往上调整堆(调整插入元素的位置)。在调整过程中,若当前节点的父亲节点小于插入元素,则将其父亲节点的值赋给当前节点,父亲节点作为当前节点,依此继续;否则当前节点即为插入位置。
  2. 大顶堆的删除:删除根,初始化最后一个元素为新根的值,然后从上往下进行调整堆(调整最后一个元素的位置)。在调整的过程中,若最后一个元素小于当前节点的孩子节点的较大值,则将孩子节点的值赋给当前节点,将孩子节点作为当前节点,依此继续;否则当前节点即为最后一个元素的位置。

【代码实现】

// maxheap_h代码
#ifndef maxheap_h
#define maxheap_h
template<class T>
class Maxheap
{
public:
    Maxheap(int size);
    ~Maxheap();
    bool Isempty();
    void push(T item);  //插入操作
    void pop();  //删除操作
    T top();
private:
    T *heap;
    int currentSize;
    int capacity;
};
//-------构造函数初始化-------
template<class T>
Maxheap<T>::Maxheap(int size)
{
  if(size<1)
  {
    throw"capacity must be >=1";
  }
  else
  {
    currentSize=0;
    capacity=size;
    heap=new T[capacity+1]; //heap[0]不使用
  }
}
//-------析构函数释放空间-------
template<class T>
Maxheap<T>::~Maxheap()
{
 delete []heap;
}
//--------判断堆是否为空-------
template<class T>
bool Maxheap<T>::Isempty()
{
 return currentSize==0;
}
//---------获取最大元素----------
template<class T>
T Maxheap<T>::top()
{
  return heap[1];
}
//-------插入操作-----
template<class T>
void Maxheap<T>::push(T item)
{
   if(currentSize==capacity)
     throw"Maxheap is full";
   else
   {
     currentSize++;
     int currentNode=currentSize;// 元素的插入位置初始化为最后
     while(currentNode>1&&heap[currentNode/2]<item)  //(从下往上)进行调整
     {
       heap[currentNode]=heap[currentNode/2];
       currentNode=currentNode/2;
     }
     heap[currentNode]=item; //插入元素
   }
}

//-----删除操作-------
template<class T>
void Maxheap<T>::pop()
{
  if(Isempty())
    throw"heap is empty ,cannot delete";
  else
  {
   T last=heap[currentSize];  //将最后一个元素初始化为根
   currentSize--;
   int currentNode=1;       
   int child=2;
   while(child<=currentSize)  //(从上往下)进行调整
   {
     if(child<currentSize&&heap[child]<heap[child+1])
        child++;
     if(last>=heap[child])
         break;
     else
     {
      heap[currentNode]=heap[child];
      currentNode=child;
      child=child*2;
     }
   }
   heap[ currentNode]=last; 
  }
}
#endif
//main.cpp
#include"maxheap.h"
#include<iostream>
using namespace std;
int main()
{
  Maxheap<int> H(100); //创建容量为100的堆
  H.push(20);
  H.push(30);
  H.push(15);
  H.push(40);
  H.push(90);
  cout<<"堆顶元素为:"<<H.top()<<endl;
  H.pop();
  cout<<"堆顶元素为:"<<H.top()<<endl;
  system("pause");
  return 0;
}

【结果】

这里写图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值