手写实现一个队列java
时间: 2024-06-01 20:01:04 浏览: 100
public class Queue {
private int[] data; // 存储数据的数组
private int head; // 队列头部指针
private int tail; // 队列尾部指针
private int size; // 队列大小
// 构造函数
public Queue(int capacity) {
data = new int[capacity];
head = 0;
tail = 0;
size = 0;
}
// 入队
public void enqueue(int value) {
if (size == data.length) {
throw new RuntimeException("Queue is full");
}
data[tail] = value;
tail = (tail + 1) % data.length;
size++;
}
// 出队
public int dequeue() {
if (size == 0) {
throw new RuntimeException("Queue is empty");
}
int value = data[head];
head = (head + 1) % data.length;
size--;
return value;
}
// 获取队头元素
public int peek() {
if (size == 0) {
throw new RuntimeException("Queue is empty");
}
return data[head];
}
// 判断队列是否为空
public boolean isEmpty() {
return size == 0;
}
// 获取队列大小
public int size() {
return size;
}
}
阅读全文