堆顶元素的获取与删除

本文介绍了一个简单的堆数据结构实现,包括插入、删除最大值及更新等操作,并通过一个示例展示了如何使用该堆进行基本的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include<iostream>
using namespace std;
class Heap {
private:
    int *data, size;
public:
    Heap(int length_input) {
        data = new int[length_input];
        size = 0;
    }
    ~Heap() {
        delete[] data;
    }
    void push(int value) {
        data[size] = value;
        int current = size;
        int father = (current - 1) / 2;
        while (data[current] > data[father]) {
            swap(data[current], data[father]);
            current = father;
            father = (current - 1) / 2;
        }
        size++;
    }
    void output() {
        for (int i = 0; i < size; i++) {
            cout << data[i] << " ";
        }
        cout << endl;
    }
    int top()
    {
        return data[0];   
    }
    void update(int pos,int n)
    {
          int lchild=2*pos+1,rchild=2*pos+2;
          int max_value=pos;
            if( lchild<n && data[lchild]>data[max_value] )
            {
                max_value=lchild;   
            }
            if(rchild<n&&data[rchild]>data[max_value])
            {
                max_value=rchild;   
            }
            if(max_value!=pos)
            {
                swap(data[pos],data[max_value]);
                update(max_value,n);   
            }
    }
    void pop()
    {
        swap(data[0],data[size-1]);   
        size--;
        update(0,size);
    }
};
int main() {
    int arr[10] = { 12, 9, 30, 24, 30, 4, 55, 64, 22, 37 };
    Heap heap(100);
    for (int i = 0; i < 10; i++) {
        heap.push(arr[i]);
    }
    
    heap.output();
    cout<<heap.top()<<endl;
    heap.pop();
    heap.output();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值