循环队列(严3.30)--------西工大NOJ习题.9_c++

 

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef struct _Queue
{
int max_size;
int rear;
int lenth;
int* data;
}Queue;
Queue* Create(int n)
{
Queue* Q = (Queue*)malloc(sizeof(Queue));
Q->data = (int*)calloc(n, sizeof(int));
Q->lenth = 0;
Q->max_size = n;
Q->rear = 0;//注意:当循环队列内部元素个数为0时,rear无意义。
return Q;
}
int Push(Queue* Q, int e)
{
if (Q->lenth == 0)
{
Q->rear = 0;
Q->lenth = 1;
Q->data[0] = e;
return 1;
}
if (Q->lenth >= Q->max_size)
{
return 0;
}
Q->rear = (Q->rear + 1) % Q->max_size;
Q->data[Q->rear] = e;
Q->lenth++;
return 1;

}
int Get_head(Queue* Q)
{
int t = Q->rear - Q->lenth + 1;
if (t < 0)
{
t = Q->max_size + t;
}
return Q->data[t];
}
int Full(Queue* Q)
{
if (Q->lenth >= Q->max_size)
return 1;
else
return 0;
}
int Empty(Queue* Q)
{
if (Q->lenth == 0)
return 1;
else
return 0;
}
void Print(Queue* Q)
{
int t = Q->rear - Q->lenth + 1;
if (t < 0)
{
t = Q->max_size + t;
}
for (int i = 0; i < Q->lenth; i++)
{
printf("%d ", Q->data[t]);
t = (t + 1) % Q->max_size;
}
}
void Read(Queue* Q)
{
char buf[12];
while (1)
{
scanf("%s", buf);
if (buf[0] == 'n')
return;
if (buf[0] == 'y')
return;
Push(Q, atoi(buf));
}
}
void Delete(Queue* Q, int e)
{
int t = Q->rear - Q->lenth + 1;
if (t < 0)
{
t = Q->max_size + t;
}
while (Q->data[t] != e)
{
Q->lenth -= 1;
t = (t + 1) % Q->max_size;
}
if (Get_head(Q) == e)
Q->lenth -= 1;
}
int main()
{
int n;
scanf("%d", &n);
Queue* Q = Create(n);
Read(Q);
int elem;
scanf("%d", &elem);
Delete(Q,elem);
Print(Q);
putchar('\n');
printf("%d", Get_head(Q));
return 0;
}