数据结构堆的有关操作.doc_第1页
数据结构堆的有关操作.doc_第2页
数据结构堆的有关操作.doc_第3页
数据结构堆的有关操作.doc_第4页
数据结构堆的有关操作.doc_第5页
全文预览已结束

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

#include#includetemplateclass minheapprivate:T *heaparray; /存放堆数据的数组int currentsize; /当前堆中的元素数目int maxsize; /最大元素数目void swap(int pos_x,int pos_y); /交换位置x和y的元素void buildheap(); /建堆public:minheap(const int n); /构造函数,参数n为堆的最大元素数目virtual minheap(); /析构函数bool isempty(); /判断堆是否为空bool isleaf(int pos)const; /判断是否为叶结点int leftchild(int pos)const; /返回左孩子的位置int rightchild(int pos)const; /返回右孩子的位置int parent(int pos)const; /返回父接点的位置bool remove(int pos,T & node); /删除给定下标的元素bool insert(const T & newnode);/向堆中插入新元素newnodeT & removemin();/从堆顶删除最小值void siftup(int position);/从position开始向上调整void siftdown(int left);/从left开始向下筛选void print();templateminheap:minheap(const int n)if(n=0)return;currentsize=0;maxsize=n;heaparray=new Tmaxsize;int a100;for(int i=0;iai;heaparraycurrentsize=ai;currentsize+;buildheap();template minheap:minheap()deleteheaparray;templatebool minheap:isleaf(int pos)constif(pos=currentsize/2)&(poscurrentsize)cout是叶结点endl;return true;elsecout不是叶结点endl;return false;templatevoid minheap:buildheap()for(int i=currentsize/2-1;i=0;i-)siftdown(i);templateint minheap:leftchild(int pos)constreturn 2*pos+1;templateint minheap:rightchild(int pos)constreturn 2*pos+2;templateint minheap:parent(int pos)constreturn(pos-1)/2;templatebool minheap:insert(const T & newnode)if(currentsize=maxsize)return false;heaparraycurrentsize=newnode;siftup(currentsize);currentsize+;return true;templateT & minheap:removemin()if(currentsize=0)coutcant delete;exit(1);elsecoutheaparray01)siftdown(0);return heaparraycurrentsize;templatebool minheap:remove(int pos,T & node)if(pos=currentsize)return false;node=heaparraypos;heaparraypos=heaparray-currentsize;if(heaparrayparent(pos)heaparraypos)siftup(pos);else siftdown(pos);return true;templatevoid minheap:siftup(int position)int temppos=position;T temp=heaparraytemppos;while(temppos0)&(heaparrayparent(temppos)temp)heaparraytemppos=heaparrayparent(temppos);temppos=parent(temppos);heaparraytemppos=temp;templatevoid minheap:siftdown(int left)int i=left;int j=leftchild(i);T temp=heaparrayi;while(jcurrentsize)if(jheaparrayj+1)j+;if(tempheaparrayj)heaparrayi=heaparrayj;i=j;j=leftchild(j);else break;heaparrayi=temp;templatevoid minheap:swap(int pos_x,int pos_y)T p;p=heaparraypos_x;heaparraypos_x=heaparraypos_y;heaparraypos_y=p;templatevoid minheap:

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论