java 实现环形数组模拟队列
- 写给自己看的(0.0)
package com.yly;
import java.util.Scanner;
public class CircularArrayQueueDome {
public static void main(String[] args) {
CircularArrayQueue circularArrayQueue = new CircularArrayQueue(5);
char key = ' ';
Scanner scanner = new Scanner(System.in);
System.out.println("s(show):显示队列");
System.out.println("a(add):添加元素");
System.out.println("g(get):取出元素");
while (true) {
key = scanner.next().charAt(0);// 一个字符
switch (key) {
case 's':
circularArrayQueue.show();
break;
case 'a':
System.out.println("请输入要添加的值");
String value = scanner.next();
circularArrayQueue.add(value);
break;
case 'g':
circularArrayQueue.get();
break;
case 'd':
circularArrayQueue.show_debug();
break;
default:
break;
}
}
}
}
// 定义一个环形数组队列
class CircularArrayQueue {
public String[] cirArrayQueue;
public int maxSize; // 定义数组长度
public int front = 0; // 定义队列头部指针
public int teal = 0; // 定义队列尾部指针
// 构造器
public CircularArrayQueue(int maxSize) {
this.maxSize = maxSize;
cirArrayQueue = new String[this.maxSize];
}
/*队列的基本原则: 先入先出
* 环形数组模拟队列的思路分析
*
* */
// 队列是否为空
public boolean isEmpty() {
return teal == front;
}
// 队列是否已经满了
public boolean isFull() {
return teal != front && teal % maxSize == front% maxSize;
}
// 队列中的成员
public int getSize() {
return teal - front;
}
// 往队列里面添加元素 teal 以字符串作为待添加的数据
public void add(String str) {
if (isFull()) { // 判断队列是否已满
System.out.println("队列已经满了");
} else {
cirArrayQueue[teal % maxSize] = str;
teal++;
System.out.printf("添加成功\t当前的teal=%d teal%%maxSize=%d", teal, teal % maxSize);
}
}
// 从队列中取出元素
public void get() {
if (isEmpty()) {
System.out.println("队列为空无法取出元素");
} else {
front++;
System.out.printf("%s被取出", cirArrayQueue[front % maxSize]);
}
}
// 查看队列中的元素
public void show() {
boolean flag = true;
int i = front;
while (flag) {
if (i == teal) {
flag = false;
}
System.out.println(cirArrayQueue[i % maxSize]);
System.out.printf("查看队列元素\t当前的i_front=%d i_front%%maxSize=%d", i, i % maxSize);
i++;
}
}
public void show_debug(){
System.out.printf("查看队列元素\t当前的front=%d front%%maxSize=%d\n", front, front % maxSize);
System.out.printf("查看队列元素\t当前的teal=%d teal%%maxSize=%d", teal, teal % maxSize);
}
}