您的位置:首页 > 其它

循环队列

2016-02-27 10:16 239 查看
如果使用数组来模拟队列,在出队时,要频繁移动队列中元素,因此使用循环队列来避免这个问题
如果头指针和尾指针所指位置之间的间隔只有一个元素,那么在次入队时,头指针和尾指针将指向同一个位置,这时将无法确定是队满,还是队空所以解决这个问题的方法有两种:1.队列中空出一个元素的位置来隔开头尾指针2.设置一个标识变量flag,当头尾指针指向位置相同时,如果队满flag = 1,队空则flag = 0;我用第一种方法。代码如下:SqQueue.h源文件:#include<stdio.h>typedef int ElemType;#define MAXSIZE 5typedef struct{ElemType data[MAXSIZE];int rear;//记录当前队列首元素位置int front;//记录当前队列尾元素的下一个位置}SqQueue;void initQueue(SqQueue * Q);//初始化队列int  queueLength(SqQueue * Q);//获取队列长度void enterQueue(SqQueue * Q,ElemType e);//入队int deQueue(SqQueue *Q);//出队int getFront(SqQueue *Q);//获取队头元素,但并不出队void printQueue(SqQueue *Q);//从头至尾打印队列中元素SqQueue.c源文件:#include"SqQueue.h"#include<time.h>void initQueue(SqQueue * Q)//初始化队列{Q->front = Q->rear = 0;printf("Init success!\n");}int  queueLength(SqQueue * Q)//获取队列长度{if (Q == NULL){printf("Queue is not inition!\n");return;}return (Q->rear - Q->front + MAXSIZE) % MAXSIZE;}void enterQueue(SqQueue * Q, ElemType e)//入队{if (Q == NULL){printf("Queue is not inition!\n");return;}if ((Q->rear + 1) % MAXSIZE == Q->front)//判断是否队满,余上MAXSIZE是为了rear处于对尾,front处于队头的情况{printf("Queue is full!\n");return;}Q->data[Q->rear] = e;//入队Q->rear = (Q->rear + 1) % MAXSIZE;}int deQueue(SqQueue *Q)//出队{if (Q == NULL){printf("Queue is not inition!\n");return;}if (Q->front == Q->rear){printf("Queue is empty!\n");_sleep(3000);exit(1);}int value =  Q->data[Q->front];Q->front = (Q->front + 1) % MAXSIZE;return value;}int getFront(SqQueue *Q)//获取队头元素,但并不出队{if (Q == NULL){printf("Queue is not inition!\n");_sleep(3000);exit(1);}if (Q->front == Q->rear){printf("Queue is empty!\n");_sleep(3000);exit(1);}return Q->data[Q->front];}void printQueue(SqQueue *Q)//从头至尾打印队列中元素{if (Q == NULL){printf("Queue is not inition!\n");return;}if (Q->front == 0 && Q->rear == 0){printf("Queue is empty!\n");return;}int pFont = Q->front;printf("Print from Queue's front!\n");while ((pFont) % MAXSIZE != Q->rear){printf("%d	\n", Q->data[pFont++]);}printf("\n");}很简单。。。
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: