本文最后更新于165 天前,其中的信息可能已经过时,如有错误请发送邮件到nullaura@outlook.com
#include <string.h>
#include <ctype.h>
// #include<malloc.h> // malloc( )等
#include <limits.h> // INT_MAX等
#include <stdio.h> // NULL等
#include <stdlib.h> // atoi( ), exit( )
#include <math.h> // floor( ), ceil( ), abs( ), OVERFLOW宏定义,其值为3。
// 函数结果状态代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW 3
typedef int Status;
typedef char QElemType; // 队列元素的数据类型
#define MAXQSIZE 5
typedef struct
{
QElemType *base; // 数组空间的起始地址
int front; // 存放队头元素的下标
int rear; // 存放队尾元素的下一个位置的下标
} SqQueue;
// 初始化空队列
void InitQueue(SqQueue &Q)
{ // 构造一个空队列Q
Q.base = (QElemType *)malloc(MAXQSIZE * sizeof(QElemType));
if (!Q.base)
exit(0);
Q.front = Q.rear = 0;
}
// 销毁队列
void DestroyQueue(SqQueue &Q)
{ // 销毁队列Q,Q不再存在
free(Q.base);
Q.front = Q.rear = 0;
}
// 清空队列
void ClearQueue(SqQueue &Q)
{ // 将Q清为空队列
Q.front = Q.rear = 0;
}
// 队列判空
Status QueueEmpty(SqQueue Q)
{ // 若队列Q为空队列,则返回TRUE;否则返回FALSE
return Q.front == Q.rear ? TRUE : FALSE;
}
// 求队列长度
int QueueLength(SqQueue Q)
{ // 返回Q的元素个数,即队列的长度
return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
// 取队头元素
Status GetHead(SqQueue Q, QElemType &e)
{ // 若队列不空,则用e返回Q的队头元素,并返回OK;否则返回ERROR
if (Q.front == Q.rear)
{
return ERROR;
}
e = Q.base[Q.front];
return OK;
}
// 入队
Status EnQueue(SqQueue &Q, QElemType e)
{ // 插入元素e为Q的新的队尾元素
if ((Q.rear + 1) % MAXQSIZE == Q.front)
{
return ERROR;
}
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return OK;
}
// 出队
Status DeQueue(SqQueue &Q, QElemType &e)
{ // 若队列不空,则删除Q的队头元素,用e返回其值,并返回OK;否则返回ERROR
if (Q.front == Q.rear)
{
return ERROR;
}
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return OK;
}
// 遍历输出队列中数据元素
void QueueTraverse(SqQueue Q, void (*visit)(QElemType))
{ // 从队头到队尾依次对队列Q中每个元素调用函数vi()
int i;
i = Q.front;
while (i != Q.rear)
{
visit(Q.base[i]);
i = (i + 1) % MAXQSIZE;
}
printf("\n");
}