c++堆栈的数组实现 cplusplus

思路

采用数组实现
堆栈的实现采用了向上插入,和向下转移的方法,具体讲解请移步
https://www.cnblogs.com/zl0372/p/min_heap.html

实现
#include<iostream>
using namespace std;
#ifndef _HEAP_H
#define _HEAP_H
template<class T>
class Heap
{
private:
    T *h;
    int MaxSize;
    int CurSize;
public:
    Heap(int n){
        h = new T[n];
        CurSize=0;
        MaxSize=n;
    }
    Heap(){
        h = (T*)malloc(10*sizeof(T));
        CurSize=0;
        MaxSize=10;
    }
    void push(T e){
        if(CurSize==MaxSize){
            cout<<"over flow"<<endl;
            return;
        }

        h[CurSize]=e;
        CurSize++;
        if(CurSize==MaxSize){
           h = (T*)realloc(h,10*sizeof(T));
           MaxSize+=10;
        }
        int currentIndex = CurSize-1;
        while(currentIndex>0){
            int parent = (currentIndex-1)/2;
            if(e<h[parent]){
                T temp = h[parent];
                h[parent] = h[currentIndex];
                h[currentIndex]=temp;

            }else{
                break;
            }

            currentIndex = parent;
        }


    }
    T pop(){
        if(CurSize==0){
            cout<<"empty"<<endl;

        }
        int cur  = 0;
        T e = h[cur];
        h[cur]=h[CurSize-1];
        CurSize--;
        while(cur<CurSize){
            int left = cur*2+1;
            int right =cur*2+2;
            if(left>=CurSize){
                break;
            }
            int maxIndex = left;
            if(right<CurSize&&h[right]<h[maxIndex]){
                maxIndex = right;
            }

            if(h[cur]>h[maxIndex]){
                T temp = h[cur];
                h[cur] = h[maxIndex];
                h[maxIndex]=temp;
            }else{
                break;
            }
            cur = maxIndex;
        }
        return e;


    }
    bool empty(){
        return CurSize==0;
    }
    ~Heap(){
        delete h;
    }


};
#endif // _HEAP_H

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值