循环队列,定义循环队列长度为10,编写初始化队列、入队、出队、求队长,实现10,20,30,40,50,60,70,80入队,10,20,30出队,56,67入队的算法功能。
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define MAXQSIZE 100//最大队列长度
#define TRUE 1
#define ERROR 0
#define OK 1
#define FALSE 0
#define OVERFLOW -1
typedef int QElemType;
typedef int Status;
/*
循环队列
*/
typedef struct {
int *base;//动态分配内存空间
int front;//头指针,若队列非空,指向队列头元素
int rear;//尾指针,若队列非空,指向队列元素的下一个位置
}SqQueue;
//初始化
void InitQueue(SqQueue &Q)
{
//构造一个空队列Q
printf("初始化队列开始\n");
Q.base = (int *)malloc(MAXQSIZE * sizeof(int));
if (!Q.base) // 存储分配失败
exit(-1);
Q.front = Q.rear = 0;
printf("初始化队列结束\n");
}
//入队
int EnQueue(SqQueue &Q, int e) {
//printf("入队开始\n");
if ((Q.rear + 1) % MAXQSIZE == Q.front) {
return -1;
}
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
//printf("入队结束\n");
return 1;
}
//出队
int DeQueue(SqQueue &Q, int &e) {
//printf("出队开始\n");
if (Q.front == Q.rear) return -1;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
//printf("%d\n", e);
//printf("出队结束\n");
return 1;
}
//求循环队列元素个数:
int QueueLength(SqQueue Q){
return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
void main() {
//SqQueue s; int main
//InitQueue(s);
//Enqueue(s, 5);
//printf("队列长度为%d\n", QueueLength(s));
//int e;
//DeQueue(s, e);
//printf("队列长度为%d\n", QueueLength(s));
//return 0;
SqQueue Q;
InitQueue(Q);
EnQueue(Q,10);
EnQueue(Q,20);
EnQueue(Q,30);
EnQueue(Q,40);
EnQueue(Q,50);
EnQueue(Q,60);
EnQueue(Q,70);
EnQueue(Q,80);
while(Q.front!=Q.rear){
QElemType e=0;
DeQueue(Q,e);
printf("%d出队\n",e);
if(Q.base[Q.front]<=30)
continue;
else{
EnQueue(Q,56);
EnQueue(Q,67);
break;
}
}
printf("队列Q:");
while(Q.front!=Q.rear){
QElemType e=0;
DeQueue(Q,e);
printf("%d ",e);
}
}
程序运行结果: