c++--堆的模拟实现

代码实现

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

typedef class Heap
{
public:
	Heap()//构造
	{
		_a = nullptr;
		_capacity = _size = 0;

	}

	Heap(Heap& p)
	{
		// 复制大小和容量
		_size = p._size;
		_capacity = p._capacity;

		// 分配新的内存
		_a = new int[_capacity];

		// 复制原对象的数据
		for (int i = 0; i < _size; ++i) {
			_a[i] = p._a[i];
		}
	}

	~Heap()//析构
	{
		delete []_a;
		_capacity = _size = 0;
	}

	Heap& operator=(const Heap& p)
	{
		if (this != &p)
		{
			delete[] _a;
			_size = p._size;
			_capacity = p._capacity;
			_a = new int[_capacity];

			for (int i = 0;i < _size;i++)
			{
				_a[i] = p._a[i];
			}
		}
		return *this;
	}

	void Swap1(int* p1,int* p2)//交换两个数据
	{
		int tmp = *p1;
		*p1 = *p2;
		*p2 = tmp;
	}

	void AdjustUp(int child)//向上调整
	{
		int parent = (child - 1) / 2;
		while (child > 0)
		{
			if (_a[child] < _a[parent])
			{
				Swap1(&_a[child], &_a[parent]);
				child = parent;
				parent = (parent - 1) / 2;
			}
			else
			{
				break;
			}
		}
	}

	void HPPush(int x)//插入
	{
		if (_size == _capacity)
		{
			int newcapacity = _capacity == 0 ? 4 : _capacity * 2;
			_capacity = newcapacity;
			int* tmp = new int[_capacity];
			for (int i = 0;i < _size;i++)
			{
				tmp[i] = _a[i];
			}
			delete[] _a;  // 释放原内存
			_a = tmp;
		}
			_a[_size] = x;
			_size++;
			AdjustUp(_size - 1);
	}

	int HPTop()//取堆顶元素
	{
		return _a[0];
	}

	void AdjustDown(int n, int parent)//向下调整
	{
		int child = parent * 2 + 1;
		while (child < n)
		{
			if (child + 1 < n && _a[child+1] < _a[child])
			{
				++child;
			}
			if (_a[child] < _a[parent])
			{
				Swap1(&_a[child], &_a[parent]);
				parent = child;
				child = parent * 2 + 1;
			}
			else
			{
				break;
			}
		}
	}

	void HPPop()//删除堆顶元素
	{
		assert(_size > 0);
		Swap1(&_a[0], &_a[_size - 1]);
		_size--;
		AdjustDown(_size, 0);
		//先进行堆尾堆顶交换,再进行重新成堆排序,不改变堆结构
	}


	int size()
	{
		return _size;
	}

	int capacity()
	{
		return _capacity;
	}

	bool HPEmpty()
	{

		return _size == 0;
	}
private:
	int* _a;
	int _size;
	int _capacity;
};

测试代码

#include"myhp.h"

void hp_test1()
{
	Heap hp;
	hp.HPPush(10);
	hp.HPPush(9);
	hp.HPPush(8);
	hp.HPPush(7);
	hp.HPPush(6);
	hp.HPPush(5);


}

void hp_test2()
{
	Heap hp;
	hp.HPPush(10);
	hp.HPPush(9);
	hp.HPPush(8);
	hp.HPPush(7);
	hp.HPPush(6);
	hp.HPPush(5);

	while (!hp.HPEmpty())
	{
		cout << hp.HPTop() << ' ';
		hp.HPPop();
	}
}

int main()
{
	hp_test2();

	return 0;
}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值