《数据结构》示范程序\优先队列的堆实现
来源:互联网 发布:北航大数据在职研究生 编辑:程序博客网 时间:2024/05/29 17:41
这是我在有关算法寄存器的网站上看到的,COPY过来,以供参考。
/*优先队列的堆实现,本程序提供了优先队列的基本操作*/
#include<stdio.h>
#include<stdlib.h>
#define MAXNUM 100
typedef int DataType;
typedef struct
{ DataType element[MAXNUM];
int n; /* n<=MAXNUM,为优先队列中元素的个数 */
}HeapPriorityQueue;
typedef HeapPriorityQueue* PHeapPriorityQueue;
int isEmpty_Heap(PHeapPriorityQueue p)
{
return p->n==0;
}
void add_Heap(PHeapPriorityQueue p, DataType x)
{ int position;
if(p->n==MAXNUM)/* 插入失败*/
{ printf("OverFlow!\n");return;}
position=p->n++;
while(position>0 && x<p->element[(position-1)/2])
{ p->element[position]=p->element[(position-1)/2];
position=(position-1)/2;
}
p->element[position]=x;
}
DataType min_Heap(PHeapPriorityQueue p)
{
return p->element[0];
}
void buildHeap (DataType* data, int heapsize, int position)
{ /*对以position所指结点为根的二叉树重建堆*/
DataType value = data[position];
while (position < heapsize)
{ int childpos = position * 2 + 1;
if (childpos < heapsize)
{ if ((childpos + 1 < heapsize) && data[childpos+1] < data[childpos])
childpos ++;
/*不变式:childpos是两个子女中较小一个的位置*/
if (value < data[childpos])
{ data[position] = value;
return;
}
else
{ data[position] = data[childpos];
position = childpos;
}
}
else
{ data[position] = value;
return;
}
}
}
void removeMin_Heap(PHeapPriorityQueue p)
{ /*从堆中移出最小元素*/
/*把最后的元素移到第一个位置*/
p->element[0] = p->element[--p->n];
/*对整个二叉树重新建堆*/
buildHeap(p->element ,p->n ,0);
}
HeapPriorityQueue queue;
int main(){
int i,key;
PHeapPriorityQueue q=&queue;
while(1){
printf("Input 1 to insert element\n"
"2 to get the smallest element\n"
"3 to delete the smallest element\n"
"else to exit\nWhat do you want to do?");
scanf("%d",&i);
if(i==1){
printf("Input the element you want to insert:");
scanf("%d",&key);
add_Heap(q, key);
}
else if(i==2){
if(isEmpty_Heap(q))
printf("There is no element!\n");
else printf("The smallest element is %d\n",min_Heap(q));
}
else if(i==3){
if(!isEmpty_Heap(q))
removeMin_Heap(q);
}
else break;
}
return 0;
}
- 《数据结构》示范程序\优先队列的堆实现
- 数据结构--优先队列(堆)的实现
- 数据结构-堆实现优先队列(java)
- 【数据结构】之用堆实现优先队列
- 【数据结构】优先队列,堆
- 数据结构:优先队列--堆
- 堆数据结构+堆排序+最大优先队列的堆的实现
- 数据结构与算法-堆、基于堆实现的优先队列、堆排序
- 堆的实现、堆排序、优先队列
- 优先队列实现堆
- 优先队列(堆实现)
- 数据结构---->优先队列(堆)
- 数据结构-堆和优先队列
- 数据结构之---优先队列(堆)
- [数据结构].堆(优先队列)
- 基于堆的优先队列的实现
- 堆和优先队列的实现
- 基于堆的优先队列实现
- android 常用控件的使用 TextView EditTextView
- 演示TDE的数据加密示例,并用logminer验证加密效果
- 面试题目收集(4)
- HDU 4217 Data Structure? 树状数组
- 写了个 大家经常会用到的 Tab 切换 效果
- 《数据结构》示范程序\优先队列的堆实现
- 数据类型
- 替换.DATA的COOKIE突破GS
- sth. about SSL (secure socket layer), JSSE (java secure socket extension)
- NAPI处理方式分析
- [Python入门及进阶笔记]Python-基础-列表及列表解析小结
- 一日一码03——插入排序
- 2014迅雷校园招聘笔试题(C++)
- 一堆开口即不说实话的人