链队列
#include <stdio.h>#include <stdlib.h>#define ElemType inttypedef 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 inttypedef 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