c++实现最大堆建立(链表结构)和堆排序

  建立最大堆并执行堆排序。


#pragma warning (disable: 4715 4018)
#ifndef MAXHEAP_H
#define MAXHEAP_H
#include<iostream>
#include<queue>
#include<stack>
#include<math.h>
class MaxHeapNode//二叉树节点类的定义。
{
	friend void Visit(MaxHeapNode *t);
	friend class MaxHeap;
public://定义构造函数。
	MaxHeapNode(const int &e)
	{
		data = e;
		LeftChild = RightChild = NULL;
	}
private:
	int data;//节点数据。
	MaxHeapNode *LeftChild;//左孩子指针。
	MaxHeapNode *RightChild;//右孩子指针。

};
//最大堆定义
class MaxHeap
{
	friend void Visit(MaxHeapNode *t);
public:
	MaxHeap() { root = NULL; size = 0; };
	int GetRoot();//根??
	void Initialize(int a[],int n);//初始化。
	MaxHeap& Insert(int *a,const int &e,int n);//插入元素
	void Delete();//删除元素。
	void HeapSort();
	void OutPutHeap(){LevelOrder(Visit);};//输出。
private:
	int size;//个数。
	 MaxHeapNode *root;//根节点。
	 MaxHeapNode *tail;//最后一个节点。
	 std::stack<MaxHeapNode*> Stack;//层序遍历将所有节点储存在栈中,将来用于删除节点和堆排序!
	void LevelOrder(void(*Visit) (MaxHeapNode *u));//层序遍历。

};
int MaxHeap::GetRoot()//得到根节点数据,用于堆排序。
{
	if (root != NULL)
		return (root->data);
	
}
void MaxHeap::LevelOrder(void(*Visit) (MaxHeapNode *u))//层序遍历。
{
	std::queue<MaxHeapNode*> Q;
	MaxHeapNode *t = root;
	while (t)
	{
		Visit(t);
		if (t->LeftChild) Q.push(t->LeftChild);
		if (t->RightChild) Q.push(t->RightChild);
		if (Q.empty())
			return;
		else
		{
			t = Q.front();
			Q.pop();
		}
	}
}
MaxHeap& MaxHeap::Insert(int *a,const int &e,int n)//定义插入。
{
	//首先判
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值