问题及代码:
1.头文件:sqqueue.h,包含定义顺序环形队列数据结构的代码、宏定义、要实现算法的函数的声明;
- #ifndef SQQUEUE_H_INCLUDED
- #define SQQUEUE_H_INCLUDED
-
- #define MaxSize 5
- typedef int ElemType;
- typedef struct
- {
- ElemType data[MaxSize];
- int front,rear;
- } SqQueue;
-
-
- void InitQueue(SqQueue *&q);
- void DestroyQueue(SqQueue *&q);
- bool QueueEmpty(SqQueue *q);
- int QueueLength(SqQueue *q);
- bool enQueue(SqQueue *&q,ElemType e);
- bool deQueue(SqQueue *&q,ElemType &e);
-
- #endif // SQQUEUE_H_INCLUDED
2.源文件:sqqueue.cpp,包含实现各种算法的函数的定义
- #include <stdio.h>
- #include <malloc.h>
- #include "sqqueue.h"
-
- void InitQueue(SqQueue *&q)
- {
- q=(SqQueue *)malloc (sizeof(SqQueue));
- q->front=q->rear=0;
- }
- void DestroyQueue(SqQueue *&q)
- {
- free(q);
- }
- bool QueueEmpty(SqQueue *q)
- {
- return(q->front==q->rear);
- }
-
-
- int QueueLength(SqQueue *q)
- {
- return (q->rear-q->front+MaxSize)%MaxSize;
- }
-
- bool enQueue(SqQueue *&q,ElemType e)
- {
- if ((q->rear+1)%MaxSize==q->front)
- return false;
- q->rear=(q->rear+1)%MaxSize;
- q->data[q->rear]=e;
- return true;
- }
- bool deQueue(SqQueue *&q,ElemType &e)
- {
- if (q->front==q->rear)
- return false;
- q->front=(q->front+1)%MaxSize;
- e=q->data[q->front];
- return true;
- }
3.在同一项目(project)中建立一个源文件(如main.cpp),编制main函数,完成相关的测试工作。 例:
- #include <stdio.h>
- #include <malloc.h>
- #include "sqqueue.h"
-
- int main()
- {
- ElemType a,x;
- SqQueue *qu;
- InitQueue(qu);
- while (1)
- {
- printf("输入a值(输入正数进队,负数出队,0结束):");
- scanf("%d", &a);
- if (a>0)
- {
- if (!enQueue(qu,a))
- printf(" 队列满,不能入队\n");
- }
- else if (a<0)
- {
- if (!deQueue(qu, x))
- printf(" 队列空,不能出队\n");
- }
- else
- break;
- }
- return 0;
- }
运行结果:
学习总结:
环形队列中:
队首指针进1:front=(front+1)%MaxSize;
队尾指针进1:rear=(rear+1)%MaxSize;