java循环队列实现
时间: 2023-12-24 11:23:29 浏览: 88
要实现循环队列,我们可以使用数组作为底层数据结构,并使用两个指针来表示队列的头部和尾部。具体实现如下:
```java
public class CircularQueue {
private int[] queue;
private int front;
private int rear;
private int size;
public CircularQueue(int capacity) {
queue = new int[capacity];
front = 0;
rear = -1;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == queue.length;
}
public void enqueue(int item) {
if (isFull()) {
throw new IllegalStateException("Queue is full");
}
rear = (rear + 1) % queue.length;
queue[rear] = item;
size++;
}
public int dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
int item = queue[front];
front = (front + 1) % queue.length;
size--;
return item;
}
public int peek() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
return queue[front];
}
public int size() {
return size;
}
}
```
使用示例:
```java
CircularQueue queue = new CircularQueue(5);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println(queue.dequeue()); // 输出:1
System.out.println(queue.peek()); // 输出:2
System.out.println(queue.size()); // 输出:2
```
阅读全文