模拟单向队列
class ArrayQueue {
private int maxSize;
private int front;
private int rear;
private int[] arr;
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
front = -1;
rear = -1;
}
// 判断是否为满
public boolean isFull() {
return rear == maxSize - 1;
}
// 判断是否为空
public boolean isEmpty() {
return rear == front;
}
// 添加数据
public void add(int data) {
if (isFull()) {
System.out.println("队列已满");
return;
}
rear++;
arr[rear] = data;
}
// 获取队列数据
public int get() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
front++;
return arr[front];
}
// 显示所有数据
public void showQueue() {
if (isEmpty()) {
System.out.println("队列为空");
return;
}
for (int i :
arr) {
System.out.println(i);
}
}
// 获取头部数据
public int getHead() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
front++;
return arr[front];
}
}
模拟双向循环队列
class ArrayQueue2 {
private int maxSize;//3
private int front;//0
private int rear;//0
private int[] arr;
public ArrayQueue2(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
front = 0;
rear = 0;
}
//判断是为为满
public boolean isFull() {
return (rear+1)%maxSize == front;
}
//判断是否为空
public boolean isEmpty() {
return rear == front;
}
//添加数据
public void add(int data) {
if (isFull()) {
System.out.println("队列已满");
return;
}
arr[rear] = data;// 0 1 2
rear = (rear+1) % maxSize;
}
// 获取队列数据
public int get() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
int value = arr[front];
front = (front+1) %maxSize;
return value;
}
// 显示所有数据
public void showQueue() {
if (isEmpty()) {
System.out.println("队列为空");
return;
}
for (int i = front; i < front + size(); i++) {
System.out.println(i%maxSize +" "+arr[i%maxSize]);
}
}
// 获取头部数据
public int getHead() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
int v=arr[front];
front++;
return v;
}
// 获取有效数据个数
public int size(){
return (rear + maxSize - front)%maxSize;
}
}
标签:return,队列,int,maxSize,rear,front,数据结构,public,模拟 From: https://www.cnblogs.com/xming2023/p/17084827.html