您的位置:首页 > 其它

顺序队列的模板

2015-12-11 00:21 288 查看
///page61操作,非链式,顺式
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef  int elemtype;
typedef int status;
#define MAXQSIZE 5 // 最大队列长度(对于循环队列,最大队列长度要减1)
struct squeue  {
elemtype *base; // 初始化的动态分配存储空间
int head; // 头指针,若队列不空,指向队列头元素
int tail; // 尾指针,若队列不空,指向队列尾元素的下一个位置
};
status InitQueue(squeue &Q)  { // 构造一个空队列Q
Q.base=(elemtype *)malloc(MAXQSIZE*sizeof(elemtype));
if(!Q.base) // 存储分配失败
exit(OVERFLOW);
Q.head=Q.tail=0;
return OK;
}
status DestroyQueue(squeue &Q)  { // 销毁队列Q,Q不再存在
if(Q.base)
free(Q.base);
Q.base=NULL;
Q.head=Q.tail=0;
return OK;
}
status ClearQueue(squeue &Q) { // 将Q清为空队列
Q.head=Q.tail=0;
return OK;
}
status QueueEmpty(squeue Q)  { // 若队列Q为空队列,则返回TRUE,否则返回FALSE
if(Q.head==Q.tail) // 队列空的标志
return TRUE;
else
return FALSE;
}
int QueueLength(squeue Q){ // 返回Q的元素个数,即队列的长度
return(Q.tail-Q.head);
}
status GetHead(squeue Q,elemtype &e) { // 若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR
if(Q.head==Q.tail) // 队列空
return ERROR;
e=*(Q.base+Q.head);
return OK;
}

status EnQueue(squeue &Q,elemtype e) { // 插入元素e为Q的新的队尾元素
if(Q.tail>=MAXQSIZE) { // 队列满,增加1个存储单元
Q.base=(elemtype *)realloc(Q.base,(Q.tail+1)*sizeof(elemtype));
if(!Q.base) // 增加单元失败
return ERROR;
}
*(Q.base+Q.tail)=e;
Q.tail++;
return OK;
}

status DeQueue(squeue &Q,elemtype &e){ // 若队列不空,则删除Q的队头元素,用e返回其值,并返回OK,否则返回ERROR
if(Q.head==Q.tail) // 队列空
return ERROR;
e=Q.base[Q.head];
Q.head=Q.head+1;
return OK;
}
void vi(elemtype e){
printf("%d ",e);

}
status QueueTraverse(squeue Q,void(*vi)(elemtype))  { // 从队头到队尾依次对队列Q中每个元素调用函数vi()。一旦vi失败,则操作失败
int i;
i=Q.head;
while(i!=Q.tail){
vi(*(Q.base+i));
i++;
}
printf("\n");
return OK;
}
status print(squeue Q){//同样输出队列
for(int i=Q.head;i<Q.tail;i++)
printf("%d ",Q.base[i]);
printf("\n");
}
int main(){
squeue q;
InitQueue(q);
elemtype e;
for(int i=5;i<=10;i++){
EnQueue(q,i);
}
printf("%d\n",QueueLength(q));
GetHead(q,e);
printf("%d\n",e);
DeQueue(q,e);
QueueTraverse(q,vi);//输出队列标准方法
print(q); //输出队列简单方法

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: