1.LinkedQueue 链式队列
#include<stdio.h>
#include<stdlib.h>
#define ERROR -1
typedef int ElementType;
typedef struct LNode * PtrNode;
//定义结点结构
struct LNode{
ElementType data;
PtrNode next;
};
//定义队列结构
typedef struct QNode * Queue;
struct QNode{
PtrNode front,rear;//定义头尾指针
};
Queue MakeEmpty(){
Queue Q=(Queue)malloc(sizeof(struct QNode));
Q->front=Q->rear=(PtrNode)malloc(sizeof(struct LNode));
Q->front->next=NULL;//头尾指针的指针域均为空
Q->rear->next=NULL;
return Q;
}
//入队列
bool AddQ(Queue Q,ElementType X){
PtrNode p=(PtrNode)malloc(sizeof(struct LNode));//申请新的结点
if(p){//若申请空间成功
p->data=X;//给申请的结点赋值X;
p->next=NULL;//新结点的指针域为空
Q->rear->next=p;//将新结点插入在原来表尾的后面
Q->rear=p;//新结点成为新的表尾
return true;
}
return false;
}
//出队列
ElementType DeleteQ(Queue Q){
if(Q->front->next==NULL) return ERROR;//若队列头指针结点的后面没有结点,则队列为空
PtrNode p=Q->front->next;//队列不为空,则找到头指针后面的结点,也即是要出队列的结点
ElementType temp=p->data;//记录要出队列结点的值
Q->front->next=p->next;//头指针next指向要删除结点的后一个结点
free(p);//释放结点p
return temp;
}
//队列的销毁 ,和链式堆栈策略相似,不再说明
bool Destroy(Queue Q){
PtrNode p=Q->front->next;
while(p){
Q->front->next=p->next;
free(p);
p=Q->front->next;
}
free(Q->front);
}
int main(){
Queue Q=MakeEmpty();
AddQ(Q,33);
AddQ(Q,44);
printf("data=%d\n",DeleteQ(Q));
printf("data=%d\n",DeleteQ(Q));
Destroy(Q);
}
2.ArrayQueue 循环队列
#include<stdio.h>
#include<stdlib.h>
#define ERROR -1
typedef int ElementType;
typedef struct QNode * Queue;
struct QNode{
ElementType *Data;
int Front;//头指针
int Rear;//尾指针
int MaxSize; //表长
};
//队列的初始化
Queue MakeEmpty(int MaxSize){
Queue Q=(Queue)malloc(sizeof(struct QNode));//给队列申请空间
Q->Data=(ElementType*)malloc(sizeof(ElementType)*MaxSize);//给数组申请空间
Q->Front=0;//头指针指向第一个元素的前一个位置,初始化为0
Q->Rear=0;//尾指针,指向最后一个元素的位置
Q->MaxSize=MaxSize;//给表长赋值
}
bool AddQ(Queue Q,ElementType X){
if((Q->Rear+1)%Q->MaxSize==Q->Front){//队列满的判定条件,首尾相连的时候满
printf("Full\n");
return false;
}
Q->Rear=(Q->Rear+1)%Q->MaxSize;//入队列时更新尾指针的位置,加1模表长
Q->Data[Q->Rear]=X;//给当前尾指针位置赋值X
return true;
}
ElementType DeleteQ(Queue Q){
if(Q->Front==Q->Rear) return ERROR;//队列空的条件是头和尾指向相同的位置
Q->Front=(Q->Front+1)%Q->MaxSize;//更新队列头指针的位置,加1模表长
return Q->Data[Q->Front]; //给当前队头的元素
}
int main(){
Queue Q=MakeEmpty(5);
AddQ(Q,33);
AddQ(Q,44);
AddQ(Q,55);
AddQ(Q,66);
AddQ(Q,77);//最多添加进去4个数据,所以77入不了队列,会打印FULL
printf("data=%d",DeleteQ(Q));
free(Q);
}