typedef struct //队列的定义
{
char data[MAXSIZE];
int front;
int rear;
}Queue;
typedef int status;
status InitQueue(Queue &Q) //队列的初始化
{
Q.front=Q.rear=0;
return OK;
}
bool IsEmptyQ(Queue &Q) //判断队列是否为空
{
if (Q.front==Q.rear)
return true;
else
return false;
}
bool IsOverQ(Queue &Q) //判断队列是否为满
{
if (((Q.rear)%MAXSIZE)==Q.front) //这里就想到钟表来理解
return true;
else
return false;
}
status InQueue(Queue &Q,char x) //入队
{
if (IsOverQ(Q)) //队满不入
return ERROR;
else
printf("请输入要入队的元素:",x);
scanf("%d",&x);
Q.data[Q.rear]=x;
Q.rear++;
}
status OutQueue(Queue &Q,char &x) //出队
{
if (IsEmptyQ(Q)) //队空不出
return ERROR;
else
printf("%d",Q.front);
Q.front++;
}
修改如下,供参考:
#include <stdio.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 50
typedef struct queue//队列的定义
{
char data[MAXSIZE];
int front;
int rear;
}Queue;
typedef int status;
status InitQueue(Queue& Q) //队列的初始化
{
Q.front = Q.rear = 0;
return OK;
}
bool IsEmptyQ(Queue& Q) //判断队列是否为空
{
if (Q.front == Q.rear)
return true;
else
return false;
}
bool IsOverQ(Queue& Q) //判断队列是否为满
{
if ((Q.rear - Q.front) > MAXSIZE)
//if (((Q.rear)%MAXSIZE)==Q.front) //这里就想到钟表来理解
return true;
else
return false;
}
status InQueue(Queue& Q, char x) //入队
{
if (IsOverQ(Q)) //队满不入
return ERROR;
else{
//printf("请输入要入队的元素:", x);
//scanf("%d", &x);
Q.data[Q.rear] = x;
Q.rear++;
}
return OK;
}
status OutQueue(Queue& Q, char & x) //出队
{
if (IsEmptyQ(Q)) //队空不出
return ERROR;
else{
x = Q.data[Q.front];
Q.front++;
}
return OK;
}
int main()
{
int i;
char ch;
Queue Q;
InitQueue(Q);
for (i = 0; i < 10; i++) //入队
InQueue(Q, i + 'A');
for (i = 0; i < 10; i++){//出队
OutQueue(Q, ch);
printf("%c\n", ch);
}
return 0;
}
定义Queue q;
调用InitQueue(q);
把这段提到主函数,可以改成while一直输入,知道输入0为止
printf("请输入要入队的元素:",x);
scanf("%d",&x);
InQueue就变成
status InQueue(Queue &Q,char x) //入队
{
if (IsOverQ(Q)) //队满不入
return ERROR;
else
Q.data[Q.rear]=x;
Q.rear++;
}
然后InQueue(q,x);