直接上代码:
#include "stdafx.h"
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAX_SIZE 6
typedef int Status; //函数返回值
typedef int QElemType; //暂定元素类型为int,可以根据自己需要修改
typedef struct
{
QElemType *base; //初始化的动态分配存储空间
int length; //队列中元素个数
int front;
int rear; //定义队尾指针
}ForQueue;
Status InitQueue(ForQueue &Q); //构造一个空队列
Status InsertQueue(ForQueue &Q,QElemType e); //插入元素e为Q的队尾元素
Status DeQueue(ForQueue &Q); //在队列不为空的情况下,删除队头元素
//入口测试函数
int _tmain(int argc, _TCHAR* argv[])
{
ForQueue Q;
if(InitQueue(Q))
{
for(int i = 0;i<MAX_SIZE; i++) //0~9自然数入队
{
if(InsertQueue(Q,i))
printf("\n入队成功:%d",i);
else printf("\n入队失败:%d",i);
}
printf("\n元素入队完毕...测试...");
for(int i = 0;i<MAX_SIZE;i++)
{
printf("\n出队元素为:%d",DeQueue(Q));
}
}
return 0;
}
Status InitQueue(ForQueue &Q) //构造一个空队列
{
Q.base = (QElemType *)malloc(MAX_SIZE * sizeof(QElemType)); //分配空间,指针指向该空间的首地址
if(!Q.base)exit(OVERFLOW);
Q.front = Q.rear = 0;
Q.length = 0; //初始长度为0
return OK;
}
Status InsertQueue(ForQueue &Q,QElemType e) //插入元素e为Q的队尾元素
{
if(Q.length == MAX_SIZE) //表明满了
return ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAX_SIZE;
Q.length++;
return OK;
}
QElemType DeQueue(ForQueue &Q ) //在队列不为空的情况下,删除队头元素
{
if(Q.length == 0)return ERROR;
else
{
QElemType e = Q.base[Q.front];
Q.front++;
Q.length--;
return e;
}
}