
package cn.redis.demo.datastructuresandalgorithms.datastructure;
import java.util.Scanner;
/**
* 数组模拟环形队列
*
* @author hq
* Created in 2020/8/23 21:44
*/
public class ArrayToQueue {
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(3);
boolean flag = true;
while (flag) {
System.out.println("a 添加,g 获取,s查询,exit 退出");
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个字母:");
String next = scanner.next();
switch (next) {
case "a":
try {
System.out.println("请输入一个数字:");
arrayQueue.add(scanner.nextInt());
} catch (Exception e) {
e.printStackTrace();
}
break;
case "g":
try {
arrayQueue.get();
} catch (Exception e) {
e.printStackTrace();
}
break;
case "s":
try {
arrayQueue.show();
} catch (Exception e) {
e.printStackTrace();
}
break;
case "exit":
flag = false;
break;
}
}
}
}
/**
* java取模(取余)%运算
* 莫不尽 取本身
* 本质是:m % n = m - (int)(m / n) * n
* 注意:余值结果符号和 m (被模数) 符号有关,m为负数则余值为负数,m为正数则余值为正数
* 例如:-187 % 100 = -187 - (int)(-187/100) * 100
* =-187 + 1 * 100
* =-187 + 100
* =-87
* 12 % 5 = 12 - (int)(12 / 5) * 5
* =12 - 2 * 5
* =2
*/
//编写一个 arrayQueue类
class ArrayQueue {
private int maxSize; //表示数组的最大容量
private int front; //列队头
private int rear; //列队尾
private int[] arr; //该数组用于存放数据,模拟列队
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[this.maxSize];
}
//判断队列是否已满
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
//判断列队是否为空
public boolean isEmpty() {
return rear == front;
}
//添加队列
public void add(int n) throws Exception {
if (isFull()) {
throw new Exception("列队已满");
}
arr[rear] = n;
rear = (rear + 1) % maxSize;
}
//获取队列中数据
public int get() throws Exception {
if (isEmpty()) {
throw new Exception("队列为空");
}
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
//显示队列中的所有元素
public void show() throws Exception {
if (isEmpty()) {
throw new Exception("队列为空");
}
for (int i : arr) {
System.out.println(i);
}
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论