题目
使用固定容量的循环数组结构实现一个简易先进先出队列(FIFO Queue),支持入队(push)、出队(pop)以及判空判满操作。
输入格式:多行指令:1 x 表示将 x 入队;0 表示出队并打印该值(队空输出 empty);-1 结束程序。
输出格式:响应出队操作,分行输出出队元素或 empty。
数据范围与约定:队列容量为 32。
思路与算法
1. 循环队列下标回绕
维护队头指针 front 和队尾指针 rear,移动时通过模运算 (idx + 1) % CAPACITY 实现数组空间的循环复用。
2. 判空与判满约定
常用方式:维护一个独立的 count 记录当前队列元素个数。入队时 count < CAPACITY,出队时 count > 0,逻辑清晰不易混淆。
完整程序
import java.util.Scanner;
public class Main {
// 循环队列实现
static class MyQueue {
private final int[] data;
private int front = 0;
private int rear = 0;
private int size = 0;
private final int capacity;
public MyQueue(int capacity) {
this.capacity = capacity;
this.data = new int[capacity];
}
public boolean push(int x) {
if (size == capacity) return false;
data[rear] = x;
rear = (rear + 1) % capacity;
size++;
return true;
}
public Integer pop() {
if (size == 0) return null;
int val = data[front];
front = (front + 1) % capacity;
size--;
return val;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
MyQueue q = new MyQueue(32);
while (sc.hasNextInt()) {
int op = sc.nextInt();
if (op == -1) {
break;
} else if (op == 1) {
int val = sc.nextInt();
q.push(val);
} else if (op == 0) {
Integer val = q.pop();
if (val == null) {
System.out.println("empty");
} else {
System.out.println(val);
}
}
}
}
}运行示例
输入:
1 10
1 20
0
0
-1输出:
10
20