队列的基本操作.docx

上传人:牧羊曲112 文档编号:3134309 上传时间:2023-03-11 格式:DOCX 页数:6 大小:37.83KB
返回 下载 相关 举报
队列的基本操作.docx_第1页
第1页 / 共6页
队列的基本操作.docx_第2页
第2页 / 共6页
队列的基本操作.docx_第3页
第3页 / 共6页
队列的基本操作.docx_第4页
第4页 / 共6页
队列的基本操作.docx_第5页
第5页 / 共6页
亲,该文档总共6页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

《队列的基本操作.docx》由会员分享,可在线阅读,更多相关《队列的基本操作.docx(6页珍藏版)》请在三一办公上搜索。

1、队列的基本操作#include #include typedef int elemType; struct QueuePtr elemType data; struct QueuePtr *next; ; struct LinkQueue struct QueuePtr *front; struct QueuePtr *rear; ; void initQueue(struct LinkQueue *Q) /*第一个操作构造一个空队列q*/ Q-front = Q-rear = NULL; /* 把队首和队尾指针置空 */ return; void push(struct LinkQueue

2、*Q, elemType x) /*第二个操作插入元素e为q的新的队尾元素 */ /* 得到一个由newP指针所指向的新结点 */ struct QueuePtr *newP; newP = (struct QueuePtr*)malloc(sizeof(struct QueuePtr); if(newP = NULL) printf(内存空间分配失败! ); exit(1); /* 把x的值赋给新结点的值域,把新结点的指针域置空 */ newP-data = x; newP-next = NULL; /* 若链队为空,则新结点即是队首结点又是队尾结点 */ if(Q-rear = NULL)

3、 Q-front = Q-rear = newP; else /* 若链队非空,则依次修改队尾结点的指针域和队尾指针,使之指向新的队尾结点 */ Q-rear = Q-rear-next = newP; /*可以分两句话来写*/ elemType pop(struct LinkQueue *Q) /*第三个操作队列不为空,则删除q的队头元素,用e返回其值,并返回ok; */ struct QueuePtr *p; elemType temp; /* 若链队为空则停止运行 */ if(Q-front = NULL) printf(队列为空,无法删除! ); exit(1); temp = Q-f

4、ront-data; /* 暂存队尾元素以便返回 */ p = Q-front; /* 暂存队尾指针以便回收队尾结点 */ Q-front = p-next; /* 使队首指针指向下一个结点 */ /* 若删除后链队为空,则需同时使队尾指针为空 */ if(Q-front = NULL) Q-rear = NULL; free(p); /* 回收原队首结点 */ return /* 返回被删除的队首元素值 */ /*第四个操作返回队列头元素*/ elemType gettop(struct LinkQueue *Q) /* 若链队为空则停止运行 */ if(Q-front = NULL) pr

5、intf(队列为空,无法删除! exit(1); return Q-front-data; /* 返回队首元素 */ ); temp; /*第五个操作判断队列是否为空*/ int emptyQueue(struct LinkQueue *Q) /* 判断队首或队尾任一个指针是否为空即可 */ if(Q-front = NULL) printf(asd); return 0; else printf(dfg); return 1; /*第六个操作清空队列*/ void clearQueue(struct LinkQueue *Q) struct QueuePtr *p = Q-front; /*

6、 队首指针赋给p */ /* 依次删除队列中的每一个结点,最后使队首指针为空 */ while(p != NULL) Q-front = Q-front-next; free(p); p = Q-front; /* 循环结束后队首指针已经为空 */ Q-rear = NULL; printf(n队列已经清空n); return; int main struct LinkQueue Q; int i; int a,b,c,d; a=b=c=d=0; / initQueue(&q); while(1) printf(n每种方法都对应一个编号,输入编号进行相应的操作。n); printf(1-操作i

7、nitQueue构造一个队列Qn); printf(2-操作gettop返回队列顶元素en); printf(3-操作enQueue插入元素e到队里尾部n); printf(4-操作pop删除Q队列的首元素n); printf(5-操作clearQueue将Q清为空队列 n); printf(6-操作emptyQueue判断Q是否为空队列,是返回0,否返回1;n); printf(7-退出程序n); printf(请选择一个基本操作:); scanf(%d,&a); switch(a) case 1:initQueue(&Q);break; case 2: c=0; c=gettop(&Q);

8、 printf(n队列头元素是%dn,c); break; case 3: printf(n请输入一个要插入队列的元素:); scanf(%d,&b); push(&Q,b);break; case 4: c=pop(&Q); printf(n删除的元素是%dn,c); break; case 5: clearQueue(&Q); break; case 6: d=emptyQueue(&Q); printf(n队列是%d 0是空,1是非空n,d); break; case 7: goto quit; default:printf(请输入1-6之间的数字。n); quit: system(pause);

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号