0
点赞
收藏
分享

微信扫一扫

c语言创建大顶堆

云上笔记 2022-01-12 阅读 97

插入和删除还没写,不过删除逻辑和创建差不多,太晚了,明天写

#include<stdio.h>
#include<stdlib.h>

typedef struct heap
{
	int* data;
	int size;
	int capacity;
}heap;

//函数:1.创建堆:返回指针、2.插入:返回指针、3.删除:返回数据、4.遍历:直接输出不返回、5.调整:返回指针、6.最大值:返回数字
heap* establish(heap*p);
heap* adjust(heap* p);
int maxnum(int a, int b);
heap* insert(heap* p);
int del(heap* p);
void ergodic(heap* p);

int main()
{
	heap* p = (heap*)malloc(sizeof(heap));
	p = establish(p);
	printf("%d\n", p->size);
	ergodic(p);
}

heap* establish(heap*p)
{
	printf("please enter  the number of data\n");
	int max;
	scanf("%d", &max);
	p->capacity = max + 1;
	p->data = (int*)malloc(sizeof(int) * p->capacity);
	p->data[0] = 9999;
	printf("please enter the data you want to type ,999 means end \n");
	for (int i = 1;; i++)
	{
		scanf("%d", &p->data[i]);
		if (p->data[i]==999)
		{
			printf("the heap is established\n");
			p->size = i - 1;
			break;
		}
		if (i==p->capacity-1)
		{
			printf("the heap is established and the capacity is full\n");
			p->size = p->capacity-1;
			break;
		}
	}
	p = adjust(p);
	return p;
}

int maxnum(int a, int b)
{
	return a > b ? a : b;
}

heap* adjust(heap* p)
{
	int lastparent, child;
	int parent = p->size / 2;
	for (; parent > 0; parent--)
	{
		lastparent = parent;
		child = parent * 2;
		for ( ; lastparent*2 <= p->size ; lastparent=child)
		{
			child = lastparent * 2;
			if (child == p->size)//only left child
			{
				int tmp = p->data[child];
				if (p->data[child] > p->data[lastparent])
				{
					p->data[child] = p->data[lastparent];
					p->data[lastparent] = tmp;
				}
			}
			else //have two childs
			{
				if (p->data[lastparent] < max(p->data[child], p->data[child + 1]))
				{
					if (p->data[child + 1] > p->data[child])
					{
						child++;
						int tmp = p->data[child];
						p->data[child] = p->data[lastparent];
						p->data[lastparent] = tmp;
					}
					else
					{
						int tmp = p->data[child];
						p->data[child] = p->data[lastparent];
						p->data[lastparent] = tmp;
					}
				}
			}
		}
	
	}
	return p;
}

void ergodic(heap* p)
{
	int i = 1;
	for ( ; i <= p->size; i++)
	{
		printf("%d\n", p->data[i]);
	}
}

举报

相关推荐

0 条评论