数据结构之循环队列
来源:互联网 发布:maven build java 编辑:程序博客网 时间:2024/05/22 14:00
数据结构之循环队列
循环队列基本的操作就是enqueue 和dequeue.队列的结构体定义如下:
struct QueueRecord{ int capacity; 总的容量 int head; 队列的头 int rear; 队列的尾 int size; int *elements; 队列中的元素。};
我们知道,判断一个队列为空和满的条件是head ==rear
.而如果实现这个条件,方法有两个:
1.寻找一个标志位以判断队列是否已经满了,如上面的size。
2. 可以空出一个队列中的元素,(rear+1)%capacity ==head
. 证明队列差一个元素就满了。
queue.h
#ifndef QUEUE_H#define QUEUE_Htypedef struct QueueRecord * Queue;int isFull(Queue Q);int isEmpty(Queue Q);Queue creatQueue(int maxElements);void makeEmpty(Queue Q);void enQueue(int value, Queue Q);int deQueue(Queue Q);#define MinQueueSize (5)struct QueueRecord{ int capacity; int head; int rear; int size; int *elements;};#endif // !QUEUE_H
queue.c
/*to realize the loop queue*/#include "queue.h"#include "stdafx.h"#include <stdio.h>#include <stdlib.h>#include "queue.h"int isFull(Queue Q){ if (Q->size == Q->capacity) { return 1; } else return 0;}int isEmpty(Queue Q){ return Q->size == 0;}void makeEmpty(Queue Q){ Q->head = 0; Q->rear = 0; Q->size = 0;}Queue creatQueue(int maxElements){ int * array; Queue Q; Q = (Queue)malloc(sizeof(struct QueueRecord)); array = (int *)malloc(sizeof(int)*maxElements); Q->capacity = maxElements; Q->head = 0; Q->rear = 0; Q->size = 0; Q->elements = array; return Q;}void enQueue(int value, Queue Q){ if ((Q->rear+1 ) % Q->capacity == Q->head) 判断一个队列是不是满了,但是差一个元素。 { printf("the queue is full\n"); } else { Q->elements[Q->rear++] = value; 每次这个函数执行完了,rear都会指向下一个位置。 if (Q->rear == Q->capacity) Q->rear = 0; }}int deQueue(Queue Q){ int temp; if (Q->head ==Q->rear) { printf("the queue is empty\n"); temp = 0; } else { temp = Q->elements[Q->head++]; head在执行一遍后也会指向下一个元素。 if (Q->head == Q->capacity) { Q->head = 0; } } return temp;}
从这个图我们可以看到rear和head之间差了一个元素,这个多余的元素作为队列满的条件。
当rear和head在程序运行过程中都指向下一个元素的时候,这个程序就没问题了。
阅读全文
0 0
- 数据结构之循环队列
- 数据结构之循环队列
- 数据结构之循环队列
- 数据结构之循环队列
- 数据结构之循环队列
- 数据结构之循环队列
- 数据结构之循环队列
- 数据结构之循环队列
- 数据结构 之 循环队列
- 数据结构之循环队列
- 数据结构之循环队列
- 数据结构之循环队列
- 复习数据结构之循环队列
- 数据结构之循环队列操作
- 数据结构之顺序循环队列
- 数据结构系列之循环队列
- 数据结构之顺序队列(循环队列)
- 【数据结构】队列-循环队列
- 面向对象
- sleep与wait区别
- HTML中的5种空格表示
- python如何找到适合需求的库
- linux安装软件
- 数据结构之循环队列
- 写作建议
- html的img中使用SVG图片做SRC在本地测试可用但是上传服务器后不能显示问题解决 标签: SVGMIME TYPE不显示服务器设置 2016-05-21 13:49 2517人阅读 评论(0)
- Java环境的配置
- 华为OJ——求小球落地5次后所经历的路程和第5次反弹的高度
- windows--reg--向注册表中写入一些数据
- The R Formula Method: The Good Parts
- axios的使用
- 学习杂谈