
package org.butupi.queue;
import java.util.Scanner;
//循环队列实现
class CircleArrayQueue {
private int[] arr;
private int rear;// end
private int front;// begin
private int size;
private final int limit; //队列最大容量
public CircleArrayQueue(int limit) {
arr = new int[limit];
rear = 0;
front = 0;
size = 0;
this.limit = limit;
}
//add
public void push(int value) {
if (this.isFull()) {
throw new RuntimeException("队列满了,不能再加了");
}
size++;
arr[rear] = value;
rear = nextIndex(rear);
}
//remove
public int pop() {
if (this.isEmpty()) {
throw new RuntimeException("队列空了,不能再拿了");
}
size--;
int ans = arr[front];
front = nextIndex(front);
return ans;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == limit;
}
// 如果现在的下标是i,返回下一个位置(关键点)代替了取模的思想
private int nextIndex(int i) {
return i < limit - 1 ? i + 1 : 0;
}
public int peek() {
return arr[front];
}
public void showQueue() {
if (this.isEmpty()) {
System.out.println("队列空");
return;
}
int tmpSize = size;
for(int i = front;tmpSize>0;i = nextIndex(i),tmpSize--) {
System.out.println(arr[i]);
}
}
}
// for test
public class RingArrayDemo {
public static void main(String[] args) {
CircleArrayQueue arrayQueue = new CircleArrayQueue(5);
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("s(show):显示队列");
System.out.println("e(exit):退出程序");
System.out.println("a(add):添加数据到队列");
System.out.println("g(get):从队列取出数据");
System.out.println("h(head):显示队列头");
System.out.print("请输入:");
key = scanner.next().charAt(0);// 接受一个字符
switch (key) {
case 's':
arrayQueue.showQueue();
break;
case 'a':
System.out.println("请输入一个数:");
int value = scanner.nextInt();
arrayQueue.push(value);
break;
case 'g':
try {
int res = arrayQueue.pop();
System.out.printf("取出的数据是%d\n", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int head = arrayQueue.peek();
System.out.printf("队列头的数据是%d\n", head);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出!");
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)