Java中怎么定义和使用循环队列,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
一、概述:
1、原理:
与普通队列的区别在于循环队列添加数据时,如果其有效数据end == maxSize - 1(最大空间)的话,end指针又移动到-1的位置
删除数据时,如果head== maxSize时 head指针移动到0的位置
2、示例图:
二、实现代码:
package com.java.queue;
/**
* @描述 对列
* @项目名称 Java_DataStruct
* @包名 com.java.stack
* @类名 Queue
* @author chenlin
* @version 1.0
* @SVN $Rev$
*/
public class CycleQueue {
private long[] arr;
private int maxSize;// 最大空间
private int len;// 有效长度
private int head;// 队头
private int end;// 队尾
public CycleQueue(int size) {
this.maxSize = size;
this.arr = new long[maxSize];
this.len = 0;
this.head = 0;
this.end = -1;
}
/**
* 从队尾插入数据
*
* @param value
*/
public void insert(long value) {
//如果满了,为什么是maxSize - 1 ,因为从-1开始
if (end == maxSize - 1) {
end = -1;
}
arr[++end] = value;
len++;
}
/**
* 从队头移除数据
*/
public long remove() {
long result = arr[head++];
if (head == maxSize) {
head = 0;
}
len--;
return result;
}
/**
* 判断是否为空
*
* @return
*/
public boolean isEmpty() {
return (len == 0);
}
/**
* 判断是否满了
*
* @return
*/
public boolean isFull() {
return (len == maxSize);
}
/**
* 获得队列的有效长度
*
* @return
*/
public int size() {
return len;
}
public static void main(String[] args) {
CycleQueue queue = new CycleQueue(50);
queue.insert(22);
queue.insert(33);
queue.insert(44);
queue.insert(534);
queue.insert(21);
queue.insert(55);
System.out.println("亿速云测试结果:");
while (!queue.isEmpty()) {
System.out.print(queue.remove() + " ");
}
System.out.println();
queue.insert(33);
queue.insert(13);
queue.insert(23);
while (!queue.isEmpty()) {
System.out.print(queue.remove() + " ");
}
}
}
运行结果:
关于Java中怎么定义和使用循环队列问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。