public class Demo {
public static void main(String[] args) {
System.out.println("测试循环队列...");
CircleArray circleArray = new CircleArray(3);
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("s(showAll): 显示队列");
System.out.println("e(exit): 退出");
System.out.println("a(add): push入队");
System.out.println("g(get): pop出队");
System.out.println("h(head): 查看队头");
key = scanner.next().charAt(0);
switch (key) {
case 's':
circleArray.showAll();
break;
case 'e':
loop = false;
break;
case 'a':
try {
System.out.println("请输入一个整数,用于入队:");
int value = scanner.nextInt();
circleArray.push(value);
System.out.println("入队成功!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'g':
try {
int value = circleArray.pop();
System.out.println("出队成功,元素为:"+value);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int value = circleArray.showPeek();
System.out.println("队列头部元素为:"+value);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
default:
System.out.println("请输入正确的指令!");
}
}
System.out.println("已退出!");
}
}
class CircleArray {
private int maxSize;
private int front;
private int rear;
private int[] queue;
public CircleArray(int maxSize) {
this.maxSize = maxSize;
queue = new int[maxSize];
}
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
public boolean isEmpty() {
return rear == front;
}
public int curSize() {
return (rear-front+maxSize)%maxSize;
}
public int showPeek() {
if (isEmpty()) {
throw new RuntimeException("队列为空...");
}
return queue[front];
}
public void push(int elm) {
if (isFull()) {
throw new RuntimeException("队列已满...");
}
queue[rear] = elm;
rear = (rear+1)%maxSize;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("队列为空...");
}
int popElem = queue[front];
front = (front+1)%maxSize;
return popElem;
}
public void showAll() {
for (int i = front; i < front+curSize(); i++) {
System.out.printf("queue[%d]= %d\n",i, queue[i]);
}
}
}
测试循环队列...
s(showAll): 显示队列
e(exit): 退出
a(add): push入队
g(get): pop出队
h(head): 查看队头
a
请输入一个整数,用于入队:
1
入队成功!
s(showAll): 显示队列
e(exit): 退出
a(add): push入队
g(get): pop出队
h(head): 查看队头
a
请输入一个整数,用于入队:
2
入队成功!
s(showAll): 显示队列
e(exit): 退出
a(add): push入队
g(get): pop出队
h(head): 查看队头
s
queue[0]= 1
queue[1]= 2
s(showAll): 显示队列
e(exit): 退出
a(add): push入队
g(get): pop出队
h(head): 查看队头
h
队列头部元素为:1
s(showAll): 显示队列
e(exit): 退出
a(add): push入队
g(get): pop出队
h(head): 查看队头
g
出队成功,元素为:1
s(showAll): 显示队列
e(exit): 退出
a(add): push入队
g(get): pop出队
h(head): 查看队头
s
queue[1]= 2
s(showAll): 显示队列
e(exit): 退出
a(add): push入队
g(get): pop出队
h(head): 查看队头
a
请输入一个整数,用于入队:
111
入队成功!
s(showAll): 显示队列
e(exit): 退出
a(add): push入队
g(get): pop出队
h(head): 查看队头
a
请输入一个整数,用于入队:
111
队列已满...
s(showAll): 显示队列
e(exit): 退出
a(add): push入队
g(get): pop出队
h(head): 查看队头
s
queue[1]= 2
queue[2]= 111
s(showAll): 显示队列
e(exit): 退出
a(add): push入队
g(get): pop出队
h(head): 查看队头
e
已退出!