烟台大学
作者 吴玉然
题目 建立顺序环形队列算法库
时间 2017 11 16
sqqueue.h 代码
typedef char ElemType;
#define MaxSize 5
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); //出队
main.cpp函数
#include <iostream>
#include "sqstack.h"
using namespace std;
int main()
{
SqQueue *s;
ElemType e;
cout << "初始化队列" << endl;
InitQueue(s);//初始化顺序环形队列
cout << "a、b、c进队" << endl;
enQueue(s, 'a');
enQueue(s, 'b');
enQueue(s, 'c');
cout << "判断队列是否为空:";
if (QueueEmpty(s))//判断顺序环形队列是否为空
cout << "空" << endl;
else
cout << "非空" << endl;
deQueue(s, e);//出队
cout << "队列中元素的个数为:"<<QueueLength(s);
enQueue(s, 'd');
enQueue(s, 'e');
enQueue(s, 'f');
cout << endl << "队列中元素的个数为:"<<QueueLength(s);
cout << endl << "删除队列" << endl;
return 0;
}
sqqeue.cpp
#include "sqstack.h"
#include <iostream>
#include <malloc.h>
using namespace std;
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->rear == q->front)
return false;
q->front = (q->front + 1) % MaxSize;
e = q->data[q->front];
return true;
}