import java.util.Scanner;
/**
*
*/
public class RingQueue<T> {
public static void main(String[] args) {
RingQueue<Integer> integerRingQueue = new RingQueue<Integer>(3);
Scanner scanner = new Scanner(System.in);
System.out.println("a:添加元素,b:获取元素,c:显示队列");
char key = ' ';
while (true){
key = scanner.next().charAt(0); // 接受第一个字符
switch (key){
case 'a':
System.out.println("输入一个数据:");
integerRingQueue.add(scanner.nextInt());
break;
case 'b':
System.out.println(integerRingQueue.get());
break;
case 'c':
integerRingQueue.getAll();
default:
break;
}
}
}
private int leader; // 起始位置
private int tail; // 结束位置,指向有效值的前一个位置
private int maxSize;
private int[] arr;
public RingQueue(Integer maxSize){
this.maxSize = maxSize;
arr = new int[maxSize];
}
// 添加元素
public void add(int value){
if (isFull()){
System.out.println("队列已满");
return;
}
arr[tail] = value;
tail = (tail+1)%maxSize;
}
// 弹出队列
public Integer get(){
if (isEmpty()){
System.out.println("队列为空");
}
int value = arr[leader];
arr[leader] = 0;
leader = (leader+1)%maxSize;
return value;
}
// 获取所有元素
public void getAll(){
if (isEmpty()){
System.out.println("队列为空");
}
for (int i =leader; i < (tail+maxSize-leader)%maxSize; i++) {
System.out.println("当前位置:"+(i%maxSize)+",值为:"+arr[i%maxSize]);
}
}
// 判断队列是否为空
public Boolean isEmpty(){
return leader == tail;
}
// 判断队列是否满
public Boolean isFull(){
if (isEmpty()){
return false;
}
return (tail+1)%maxSize == leader;
}
}
数组实现环形队列
最新推荐文章于 2022-05-09 21:58:00 发布