循环队列
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");}很简单。。。
相关文章推荐
- BZOJ3670: [Noi2014]动物园
- 深入使用Spring
- 修改表名称?
- linux内核super_block结构分析
- 剑指offer相关题目,输入两个字符串,从第一个字符串中删除在第二个字符串中出现的所有字符
- 如何提升理解力
- 创建表?
- UIWebView
- tomcat站点配置
- linux内核dentry结构分析
- DIV+CSS命名规范-转载2
- LA 3029 - City Game (模拟&技巧)好题
- sqoop job命令自动生成
- Android-实现底部切换标签(fragment)
- mysql学习笔记
- 其他数据类型?
- JqGrid实现自定义查询
- sqoop job命令自动生成
- solr实体嵌套、字段加权查询
- Codepage、Unicode、ANSI等学习记录