介绍:本来是打算不添加任何打印说明的,怕有的人看不懂,所以加了一下。
初学这可以复制去运行一下分析每个函数是怎么实现的
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define Elemtype int
#define MAX_QUEUE 8//最大数量为8个
typedef struct Queue{
Elemtype *base;//基地址
int front;//队头头
int tail;//队尾
}Queue;
void InitQueue(Queue *Q)//初始化队列
{
Q->base=(Elemtype*)malloc(sizeof(Elemtype)*MAX_QUEUE);
Q->front=Q->tail=0;
}
void EnQueue(Queue *Q,Elemtype x)//入队
{
if((Q->tail+1)%MAX_QUEUE==Q->front)
{
printf("已满\n");
return;
}
Q->base[Q->tail]=x;
Q->tail=(Q->tail+1)%MAX_QUEUE;
printf("%d已经入队\n",x);
}
void show(Queue *Q)//展示队列
{
for(int i=Q->front;i!=Q->tail;)
{
printf("%d ",Q->base[i]);
i=(i+1)%MAX_QUEUE;
}
printf("\n");
}
void DeQueue(Queue *Q)//出队
{ printf("%d出队\n",Q->base[Q->front]);
Q->front=(Q->front+1)%MAX_QUEUE;
}
int lenQueue(Queue *Q)
{
return (Q->tail-Q->front);
}
void Gethead(Queue *Q,Elemtype *x)//获取对头元素
{
if(Q->front==Q->tail)
return;
*x=Q->base[Q->front];
}
void ClearQueue(Queue *Q)//清空
{
Q->front=Q->tail=0;
}
void DestroyQueue(Queue *Q)//销毁
{
ClearQueue(Q);
free(Q->base);
Q->base=NULL;
}
int main()
{ int x;
Queue Q;
InitQueue(&Q);
EnQueue(&Q,1);
EnQueue(&Q,2);
EnQueue(&Q,3);
EnQueue(&Q,4);
DeQueue(&Q);
show(&Q);
printf("队列长%d\n",lenQueue(&Q));
Gethead(&Q,&x);
printf("队头元素为%d\n",x);
}