设计循环队列(JAVA 实现)
设计自己的循环队列
- add (入队,添元素)
- remove (出队,删除队首元素并返回)
- element (查看,查看队首元素)
- show (显示数据(遍历))
private int maxSize;//表示数组的最大容量
private int front;// 队列的第一个元素 front=0;
private int rear;//队列尾
private int[] arr;
public circlequeue(int arrMaxSize){
maxSize = arrMaxSize;
arr = new int[maxSize];
}
//判断队列是否满
public boolean isFull(){
return (rear+1)%maxSize ==front;
}
//判断是否为空
public boolean isEmpty(){
return rear == front;
}
//添加数据元素
public void add(int n){
if (isFull()){
System.out.println("队列已满 不可添加");
return;
}
arr[rear] = n;
rear = (rear+1)%maxSize;
}
//出队
public int remove(){
if (isEmpty()){
throw new RuntimeException("队列空,不可取数据");
}
//创建临时变量 1将front 保存上,2再将front后移,3将临时变量返回
int val = arr[front];
front = (front+1)%maxSize;
return val;
}
//显示数据
public void showQueue(){
if (isEmpty()){
System.out.println("队列为空 没有输出");
return;
}
//遍历
for (int i = front; i< front+size(); i++){
System.out.printf("arr[%d]=%d\n",i%maxSize,arr[i%maxSize]);
}
}
public int size(){
return (rear+maxSize-front)%maxSize;//有效元素的个数
}
//element
public int element(){
if (isEmpty()){
System.out.println("队列为空,没有数据");
}
return arr[front];// 是因为front 是头元素;
}
- 力扣622 添加链接描述
- 在上述循环基础上进行简单修改;
class MyCircularQueue {
private int maxSize;
private int front;
private int rear;
private int[] arr;
int sign =0;
public MyCircularQueue(int k) {
arr = new int[k];
maxSize = k;
}
public boolean enQueue(int value) {//add
if (isFull()){
return false;
}
arr[rear] = value;
rear = (rear+1)%maxSize;
sign=1;
return true;
}
public boolean deQueue() {//remove
if (isEmpty()){
return false;
}
front = (front+1)%maxSize;
sign =0;
return true;
}
public int Front() {
if (isEmpty()){
return -1;
}
return arr[front];
}
public int Rear() {//获取队尾元素
if (isEmpty()){
return -1;
}
if(front==rear){
int temp=rear-1;
if(temp<0) temp=maxSize+temp;
return arr[temp];
}
else {
if(rear-1<0){
return arr[maxSize+(rear-1)];
}
else return arr[rear-1];
}
}
public boolean isEmpty() {
if(sign==0 && front==rear) return true;
else return false;
}
public boolean isFull() {
if(sign==1 && front==rear) return true;
else return false;
}
}