第七周项目二
- /*
- 烟台大学计算机学院
- 文件名称:xiangmu.cpp
- 作者:刘照京
- 完成日期:2017年10月26日
- 问题描述:定义链队存储结构,实现其基本运算,并完成测试。
- 输入描述:无
- 输出描述:队列元素,出列入列元素测试结果
- */
- LQN.h:
- #include <stdio.h>
- #include <malloc.h>
- typedef int ElemType;
- typedef struct qnode
- {
- ElemType data;
- struct qnode *next;
- }DataNode;
- typedef struct
- {
- DataNode *front;
- DataNode *rear;
- }LinkQuNode;
- void InitQueue(LinkQuNode *&q); //初始化顺序环形队列
- void DestroyQueue(LinkQuNode *&q); //销毁顺序环形队列
- bool QueueEmpty(LinkQuNode *q); //判断顺序环形队列是否为空
- int QueueLength(LinkQuNode *q); //返回队列中元素个数,也称队列长度
- bool enQueue(LinkQuNode *&q,ElemType e); //进队
- bool deQueue(LinkQuNode *&q,ElemType &e); //出队
- LQN.cpp:
- #include "LQN.h"
- void InitQueue(LinkQuNode *&q)
- {
- q=(LinkQuNode *)malloc(sizeof(LinkQuNode));
- q->front=q->rear=NULL;
- }
- void DestroyQueue(LinkQuNode *&q)
- {
- DataNode *pre=q->front,*p;
- if(pre!=NULL)
- {
- p=pre->next;
- while(p!=NULL)
- {
- free(pre);
- pre=p;
- p=p->next;
- }
- free(pre);
- }
- free(q);
- }
- bool QueueEmpty(LinkQuNode *q)
- {
- return(q->rear==NULL);
- }
- int QueueLength(LinkQuNode *q)
- {
- int i=0;
- DataNode *p;
- p=q->front;
- while(p!=NULL)
- {
- i++;
- p=p->next;
- }
- return i;
- }
- bool enQueue(LinkQuNode *&q,ElemType e)
- {
- DataNode *p;
- p=(DataNode*)malloc(sizeof(DataNode));
- p->data=e;
- p->next=NULL;
- if(q->rear==NULL)
- {
- q->front=q->rear=p;
- }
- else
- {
- q->rear->next=p;
- q->rear=p;
- }
- }
- bool deQueue(LinkQuNode *&q,ElemType &e)
- {
- DataNode *t;
- if(q->rear==NULL)
- return false;
- t=q->front;
- if(q->front==q->rear)
- q->front=q->rear=NULL;
- else
- q->front=q->front->next;
- e=t->data;
- free(t);
- return true;
- }
- main:
- #include <stdio.h>
- #include "LQN.h"
- int main()
- {
- ElemType e;
- LinkQuNode *q;
- printf("(1)初始化链队q\n");
- InitQueue(q);
- printf("(2)依次进链队元素a,b,c\n");
- enQueue(q,'a');
- enQueue(q,'b');
- enQueue(q,'c');
- printf("(3)链队为%s\n",(QueueEmpty(q)?"空":"非空"));
- if (deQueue(q,e)==0)
- printf("队空,不能出队\n");
- else
- printf("(4)出队一个元素%c\n",e);
- printf("(5)链队q的元素个数:%d\n",QueueLength(q));
- printf("(6)依次进链队元素d,e,f\n");
- enQueue(q,'d');
- enQueue(q,'e');
- enQueue(q,'f');
- printf("(7)链队q的元素个数:%d\n",QueueLength(q));
- printf("(8)出链队序列:");
- while (!QueueEmpty(q))
- {
- deQueue(q,e);
- printf("%c ",e);
- }
- printf("\n");
- printf("(9)释放链队\n");
- DestroyQueue(q);
- return 0;
- }
运行结果
学习心得:学会了链队环形队列的基本操作。