赞
踩
目录
队列:只能在一端进行插入数据操作,另一端进行删除数据操作的特殊线性表,是一种先进先出的存储结构
插入操作的一端为队尾,删除操作的一端为队头
在线性队列中,一旦队列满了,即使队列的前面有空间,我们也不能插入下一个元素,这时,我们可以使用循环队列,来使用这些空间存储新的值
循环队列: 队头和队尾相连接的队列
我们使用数组来实现循环队列,通过构造器,来创建队列,并设置队列的大小为n
- class MyCircularQueue {
- private int[] elem;
- private int front;
- private int rear;
- private int size;
- public MyCircularQueue(int n) {
- elem = new int[n+1];
- front = rear = 0;
- size = n + 1;
- }
- }
在创建队列时,我们预留一个空间,以便判断队列满和计算队列元素个数
判断循环队列是否为空
当队头和队尾指向同一位置时,队列是空的
-
- public boolean isEmpty() {
- return front == rear;
- }
判断循环队列是否已满
若队尾的下一个位置是队头,那么循环队列已满
当rear指向最后一个位置时,+1会造成越界,此时我们通过取余(%),让其指向0位置处
- public boolean isFull() {
- return ((rear+1)%size == front);
- }
添加数据
首先判断队列是否已满,若已满,添加失败,返回false,若没有,则在队尾rear位置添加数据,并将rear向后移动
- public boolean enQueue(int value) {
- //判断队列是否满
- if(isFull()){
- return false;
- }else {
- elem[rear] = value;
- rear = (rear+1)%size;
- return true;
- }
- }
删除数据
首先判断队列是否为空,若为空,删除失败,返回false,若不为空,则将front向后移动
- public boolean deQueue() {
- //队列是否为空
- if(isEmpty()){
- return false;
- }else {
- front = (front + 1) % size;
- return true;
- }
- }
获取队头元素
首先判断队列是否为空,若为空,队列中无元素,抛出异常,若不为空,返回队头元素,并将front向后移动
- public int getFront() {
- if(isEmpty()){
- throw new RuntimeException("队列为空,无元素!");
- }else {
- int val = elem[front];
- front = (front + 1) % size;
- return val;
- }
- }
计算队列中元素个数
- public int size(){
- return (rear + size - front) % size;
- }
完整代码
- class MyCircularQueue {
- private int[] elem;
- private int front;
- private int rear;
- private int size;
- public MyCircularQueue(int n) {
- elem = new int[n+1];
- front = rear = 0;
- size = n + 1;
- }
- public boolean isEmpty() {
- return front == rear;
- }
-
- public boolean isFull() {
- return ((rear+1)%size == front);
- }
-
- public boolean enQueue(int value) {
- //判断队列是否满
- if(isFull()){
- return false;
- }else {
- elem[rear] = value;
- rear = (rear+1)%size;
- return true;
- }
- }
-
- public boolean deQueue() {
- //队列是否为空
- if(isEmpty()){
- return false;
- }else {
- front = (front + 1) % size;
- return true;
- }
- }
- public int getFront() {
- if(isEmpty()){
- throw new RuntimeException("队列为空,无元素!");
- }else {
- int val = elem[front];
- front = (front + 1) % size;
- return val;
- }
- }
- public int size(){
- return (rear + size - front) % size;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。