循环队列的实现
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define MAXSIZE 5
#define SIZE (MAXSIZE - 1)
typedef struct data {
int n;
}Data;
typedef struct {
Data data[MAXSIZE];
int front;
int rear;
}Queue;
bool InitQueue(Queue* pq);
bool QueueIsEmpty(Queue* pq);
bool QueueIsFull(Queue* pq);
bool InQueue(Queue* pq, Data data);
bool OutQueue(Queue* pq);
void ShowQueue(Queue* pq);
bool InitQueue(Queue* pq)
{
pq->front = pq->rear = 0;
if (pq->front == 0 && pq->rear == 0)
return true;
else return false;
}
bool QueueIsEmpty(Queue* pq)
{
if (pq->front == pq->rear)
{
printf("队列为空!\n");
return true;
}
else return false;
}
bool QueueIsFull(Queue* pq)
{
if (SIZE == (pq->rear + MAXSIZE - pq->front) % MAXSIZE)
{
printf("队列已满!\n");
return true;
}
else return false;
}
bool InQueue(Queue* pq, Data data)
{
if (QueueIsFull(pq) == true)
return false;
else
{
pq->rear = (pq->rear + 1) % MAXSIZE;
pq->data[pq->rear] = data;
return true;
}
}
bool OutQueue(Queue* pq)
{
if (QueueIsEmpty(pq) == true)
return false;
else
{
pq->front = (pq->front + 1) % MAXSIZE;
printf("出队成功!\n");
return true;
}
}
void ShowQueue(Queue* pq)
{
int size = (pq->rear + MAXSIZE - pq->front) % MAXSIZE;
int i = 1;
if (QueueIsEmpty(pq) == false)
{
for (i; i <= size; i++)
printf("%d ", pq->data[(pq->front + i) % MAXSIZE].n);
}
}
int main()
{
Queue Q;
Data temp = {0};
if (InitQueue(&Q) == true)
{
printf("程序运行……\n");
system("pause");
system("cls");
printf("本队列长:%d\n", SIZE);
}
else
exit(1);
for (int i = 0; i < SIZE; i++)
{
scanf("%d", &temp.n);
while (getchar() != '\n')
continue;
InQueue(&Q, temp);
}
OutQueue(&Q);
ShowQueue(&Q);
return 0;
}