顺序队列基本操作:初始化、销毁、判断是否为空、进队出队
循环队列基本操作:已知队尾指针和元素个数可以计算出队头指针,设计这种环形队列的初始化、进队、出队判断是否为空
链队:类型定义、初始化、判断是否为空、销毁
注释要尽量详细,让初学者看得懂
注意,请分为三段代码,要有主函数,最终能顺利运行,不要使用c++,只用c语言完成,大概效果图跟这个一样
#include<stdio.h>
#define MaxSize 5
typedef int ElemType;
struct Queue
{
ElemType data[MaxSize];
int rear,front; //队尾,队头下标
};
//判断队列是否为空
int isEmpty(struct Queue *Q){
return Q->rear==Q->front;
}
//初始化队列
int InitQueue(struct Queue *Q){
Q->rear=0;
Q->front=0;
}
//入队
int EnQueue(struct Queue *Q,ElemType x){
if (Q->rear>=MaxSize)
{
return 0;
}
Q->data[Q->rear++]=x;
return 1;
}
//出队
int DeQueue(struct Queue *Q,ElemType *x){
if (isEmpty(Q))
{
return 0;
}
*x=Q->data[Q->front++];
return 1;
}
//销毁队列
int DestroyQueue(struct Queue *Q){
ElemType x;
while (!isEmpty(Q))
{
DeQueue(Q,&x);
}
return 1;
}
#include<stdio.h>
#define MaxSize 5
typedef int ElemType;
struct CQueue
{
ElemType data[MaxSize];
int rear,num; //num是队列元素个数
};
int InitCQueue(struct CQueue *Q){
Q->rear=0;
Q->num=0;
return 1;
}
int isEmpty(struct CQueue *Q){
return Q->num==0;
}
int EnQueue(struct CQueue *Q,ElemType x){
if (Q->num>=MaxSize)
{
return 0;
}
Q->data[Q->rear]=x;
Q->rear=(Q->rear+1)%MaxSize;
Q->num++;
return 1;
}
int DeQueue(struct CQueue *Q,ElemType *x){
if (isEmpty(Q))
{
return 0;
}
int front=(Q->rear-Q->num+MaxSize)%MaxSize;
*x=Q->data[front];
Q->num--;
return 1;
}
int DestroyCQueue(struct CQueue *Q){
ElemType x;
while (!isEmpty(Q))
{
DeQueue(Q,&x);
}
return 1;
}
#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
//链式队列
//链队的数据存储方式
struct LinkNode
{
ElemType data;
struct LinkNode *next;
};
//链队的头尾指针
struct LinkQueue
{
struct LinkNode *front,*rear;
};
int InitQueue(struct LinkQueue *Q){
Q->front=Q->rear=(struct LinkNode *)malloc(sizeof(struct LinkNode)); //建立头节点
Q->front->next=NULL;
return 1;
}
int isEmpty(struct LinkQueue *Q){
return Q->front==Q->rear;
}
//入队
int EnQueue(struct LinkQueue *Q,ElemType x){
//链队一般不会存满,无需判满
struct LinkNode *s=(struct LinkNode *)malloc(sizeof(struct LinkNode));
s->data=x;
s->next=NULL;
Q->rear->next=s;
Q->rear=s;
return 1;
}
//出队
int DeQueue(struct LinkQueue *Q,ElemType *x){
if(isEmpty(Q)){
return 0;
}
struct LinkNode *p=Q->front->next;
*x=p->data;
Q->front->next=p->next;
if (Q->rear==p)
{
Q->rear=Q->front; //如果队列里只剩下一个要删除的节点,那么此节点删除后,头尾指针要指向同一个地方
}
free(p);
return 1;
}
//销毁队列
int DestroyQueue(struct LinkQueue *Q){
ElemType x;
while (!isEmpty(Q))
{
DeQueue(Q,&x);
}
return 1;
}