队列和栈有所不同,栈是先进后出,而队列是先进先出
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
const int max = 10;
struct queue{
int *num;/* 储存元素的指针 */
int rear;/* 队列的尾指针 */
int front;/* 队列的头指针 */
int maxsize;/* 队列的容量 */
};
typedef struct queue *Queue;
/*判断队列是否为空*/
bool isempty(Queue q)
{
return (q->front == q->rear);
}
/*判断队列是否为满*/
bool isfull(Queue q)
{
return ((q->rear + 1)%max == q->front);
}
/*创建一个初始的队列*/
Queue create(int max)
{
Queue q = (Queue)malloc(sizeof(struct queue));
q->num = (int*)malloc(max * sizeof(struct queue));
q->front = q->rear = 0;
q->maxsize = max;
return q;
}
/*向队列里加元素(入队)*/
void add(Queue q, int number)
{
if(isfull(q) == true)
{
printf("队列满!");
}
else
{
q->rear = (q->rear + 1)%q->maxsize;
q->num[q->rear] = number;
}
}
/*将元素从队列中弹出(出队)*/
int del(Queue q)
{
if(isempty(q) == true)
{
printf("队列空!");
}
else
{
q->front = (q->front + 1)%q->maxsize;
return q->num[q->front];
}
}
void print(Queue q,int n)
{
for(int i = 1;i <= n; i++)
{
printf("%d ",q->num[i]);
}
printf("\n");
}
int main(void)
{
Queue q = create(max);
int number,n;
scanf("%d",&n);
for(int i = 0; i< n; i++)
{
scanf("%d",&number);
add(q,number);
}
print(q,n);
for(int i = 1; i <= n; i++)
{
printf("%d\n",del(q));
}
return 0;
}