队列实现

链队列

 

#include <stdio.h>
#include <stdlib.h>
#define ElemType int
typedef struct QNode{
ElemType data;
struct QNode *next;
}QNode,*QueuePtr;//结点结构体
typedef struct{
QueuePtr front;//头结点
QueuePtr rear;//尾结点
}LinkQueue;//链式队列结构体
void InitQueue(LinkQueue *q){
q->front=(QueuePtr)malloc(sizeof(QNode));
q->rear=q->front;
q->front->next;
}//初始化队列
void EnQueue(LinkQueue *q,ElemType e){
QueuePtr r;
r=(QueuePtr)malloc(sizeof(QNode));
r->data=e;
r->next=NULL;
q->rear->next=r;
q->rear=r;
}//将元素e插入队列
void DeQueue(LinkQueue *q,ElemType &e){
QueuePtr r;
if(q->rear==q->front){printf("当前队列为空:");}
else{
e=q->front->next->data;
r=q->front->next;
q->front->next=q->front->next->next;
if(r==q->rear){q->rear=q->front;}//若当前只有一个结点,删除后队列为空
free(r);
}
}//将元素出队
void PrintQueue(LinkQueue *q){
QueuePtr p;
p=q->front->next;
printf("队列中的元素:");
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}//打印出当前队列中的元素
bool EmptyQueue(LinkQueue *q){
if(q->front==q->rear){printf("队列为空\n");return true;}
else {printf("队列不为空\n");return false;}
}
int main(){
LinkQueue LQueue;
ElemType e;
InitQueue(&LQueue);
EnQueue(&LQueue,1);
EnQueue(&LQueue,2);
EnQueue(&LQueue,3);
PrintQueue(&LQueue);
DeQueue(&LQueue,e);
printf("出队元素:%d\n",e);
EmptyQueue(&LQueue);
PrintQueue(&LQueue);
}

 

循环队列

 

#include <stdio.h>
#include <stdlib.h>
#define MaxSize 6
#define ElemType int
typedef struct{
ElemType data[MaxSize];
int front;
int rear;
}SqQueue;
void InitCqueue(SqQueue *q){
q->front=q->rear=0;
}//初始化循环队列
void EnCqueue(SqQueue *q,ElemType e){
if((q->rear+1)%MaxSize==q->front){printf("循环队列已满\n");}
else {
q->data[q->rear]=e;
q->rear=q->rear+1;
}
}//将元素e插入循环队列
void DeCqueue(SqQueue *q){
if(q->rear==q->front){printf("循环队列以空\n");}
else{
q->front=(q->front+1)%MaxSize;
}
}//删除元素
void PrintCqueue(SqQueue *q){
printf("循环队列中的元素:");
int p=q->front;
while(p!=q->rear){
printf("%d ",q->data[p]);
p=p+1;
}
printf("\n");
}//打印循环队列
void EmptyCqueue(SqQueue *q){
if(q->front==q->rear){printf("队列为空\n");}
else printf("队列不空\n");
}//判断是否为空
void main(){
SqQueue Q;
InitCqueue(&Q);
EmptyCqueue(&Q);
EnCqueue(&Q,1);
EnCqueue(&Q,2);
EnCqueue(&Q,3);
EnCqueue(&Q,4);
EnCqueue(&Q,5);
PrintCqueue(&Q);
EmptyCqueue(&Q);
DeCqueue(&Q);
PrintCqueue(&Q);
EnCqueue(&Q,6);
PrintCqueue(&Q);
}

 

转载于:https://www.cnblogs.com/Yshun/p/11172464.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值