数据结构与算法之环形队列实现(改良)
程序员文章站
2022-07-09 15:50:48
...
解决的初级队列无法复用的问题
public class CircleArrayQueueDemo {
public static void main(String[] args) {
CircleArray queue = new CircleArray(4);
//对象接收数据
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("s(show) 显示队列");
System.out.println("a(add) 添加数据到队列");
System.out.println("g(get) 从队列取出数据");
System.out.println("h(head) 查看队列头数据");
System.out.println("e(exit) 退出");
key = scanner.next().charAt(0);
switch (key) {
case 's':
queue.showQueue();
break;
case 'a':
System.out.println("输入一个数字");
int n = scanner.nextInt();
queue.add(n);
break;
case 'g':
try {
int res = queue.getQueue();
System.out.printf("取出的数字为%d\n", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = queue.headQueue();
System.out.printf("头数据为%d\n", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
class CircleArray {
private int maxSize;
//这里的rear的定义是,指向最后一个元素的下一个位置;给最后一个元素当作标志位,实际容量是maxSize-1;
private int rear;
//定义是队列的第一个元素
private int front;
private int[] arr;
//1.创建构造器,初始化数据
public CircleArray(int size) {
this.maxSize = size;
rear = 0;
front = 0;
arr = new int[maxSize];
}
//2.判断是否为空
public boolean isEmpty() {
return rear == front;
}
//3.判断是否满了
public boolean isFull() {
//判断为空,并且给队列预留一个位置,动态判断
return (rear + 1) % maxSize == front;
}
//4.添加方法
public void add(int n) {
if (isFull()) {
System.out.println("队列满了,不能添加数据");
return;
}
arr[rear] = n;
//这里需要取模,因为到最后一个元素再添加元素的话,会出现越界,这里会使rear变为0
rear = (rear + 1) % maxSize;
}
//5.取出方法
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空,不能取数据");
}
//这里把front对应的值保存一下,不然无法后移
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
//6.显示队列方法
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]);
}
}
//7.定义一个返回队列有效值的方法
public int size() {
return (rear + maxSize - front) % maxSize;
}
//8.查看头数据
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空的,没有数据~~");
}
return arr[front];
}
}