#include <stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define Ok 1
#define Error 0
typedef int QElemType;
typedef int Status;
typedef struct {
QElemType *front;
QElemType *rear;
int length;
}SqQueue; //顺序队列结构体的定义
Status Ini_Queue(SqQueue &S) //初始化顺序队列(和栈的初始化一样)
{
S.front=(QElemType*)malloc(STACK_INIT_SIZE*sizeof(SqQueue));
if(!S.front) {printf("出错了"); return Error;}
S.rear=S.front;
S.length=STACK_INIT_SIZE;
return Ok;
}
Status In_SqQueue(SqQueue &S,QElemType e ) // 向顺序队列中插入元素(通过移动rear和front指针)
{
if(S.rear-S.front>=S.length) //如果超过了之前定义的队列的大小,则用realloc函数再为队列扩大空间
{
S.front=(QElemType*)realloc(S.front,S.length+STACKINCREMENT*sizeof(SqQueue));
if(!S.front) { printf("出错了啊"); return Error;}
S.rear=S.front+STACK_INIT_SIZE;
S.length=S.length+STACKINCREMENT;
}
*S.rear++=e;
return Ok;
}
Status Out_SqQueue(SqQueue &s,QElemType &e)
{
e=*s.front++;
return Ok;
}
/*void print(SqQueue S) //用从rear到front指针的移动来输出队列中的所有元素
{
int i;
for(i=0;i<S.rear-S.front;i++)
{
printf("%d",S.front[i]);
}
printf("\n");
}*/
void print(SqQueue s ) //利用出栈函数的输出
{
int e,i ;
while(s.front!=s.rear)
{
Out_SqQueue(s,e);
printf("%d",e);
}
}
void main()
{
SqQueue S;int e;
Ini_Queue(S);
printf("请输入顺序队列的值:");
scanf("%d",&e);
while(e!=0)
{
In_SqQueue(S,e);
scanf("%d",&e);
}
print(S);
getchar();
getchar();
}
顺序队列基本和栈是相同的,只是在输出操作是先进先出,栈是先进后出