大家好,又见面了,我是你们的朋友全栈君。
环形队列可以使用数组实现,也可以使用循环链表实现。
package www.bittech;
public class MyCircularQueue {
private int front;//队列头
private int rear;//队列尾
private int usedSize;//数据个数
private int[] elem;//数组
public MyCircularQueue(int k){
this.elem=new int[k];
this.front=0;
this.rear=0;
this.usedSize=0;
}
public boolean enQueue(int value){
if(isFull()){
return false;
}
this.elem[this.rear]=value;
this.usedSize++;
this.rear=(this.rear+1)%this.elem.length;
return true;
}
//队尾下标加上1在%
public boolean isFull(){
if((this.rear+1)%this.elem.length==this.front){
return true;
}
return false;
}
public boolean isEmpty(){
return this.rear==this.front;
}
public boolean deQueue(int value){
if(isEmpty()){
return false;
}
this.elem[front]=value;
this.front=(this.front+1)%this.elem.length;
this.usedSize--;
return true;
}
public int Front(){
if(isEmpty()){
throw new UnsupportedOperationException("队列为空");
}
return this.elem[this.front];
}
public int Rear(){
if(isEmpty()){
throw new UnsupportedOperationException("队列为空");
}
int index=this.rear == 0 ? this.elem.length-1 : this.rear-1;
return this.elem[index];
}
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/125500.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有