用java实现循环队列
时间: 2023-07-17 12:55:42 浏览: 105
在Java中,你可以使用数组来实现循环队列。下面是一个简单的示例代码:
```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 = -1;
rear = -1;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == queue.length;
}
public void enqueue(int item) {
if (isFull()) {
System.out.println("Queue is full. Cannot enqueue more items.");
return;
}
if (isEmpty()) {
front = 0;
}
rear = (rear + 1) % queue.length;
queue[rear] = item;
size++;
System.out.println("Enqueued: " + item);
}
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty. Cannot dequeue any items.");
return -1;
}
int item = queue[front];
queue[front] = 0;
if (front == rear) {
front = -1;
rear = -1;
} else {
front = (front + 1) % queue.length;
}
size--;
System.out.println("Dequeued: " + item);
return item;
}
public void display() {
if (isEmpty()) {
System.out.println("Queue is empty.");
return;
}
System.out.print("Queue: ");
for (int i = 0; i < size; i++) {
int index = (front + i) % queue.length;
System.out.print(queue[index] + " ");
}
System.out.println();
}
public static void main(String[] args) {
CircularQueue queue = new CircularQueue(5);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
queue.display();
queue.dequeue();
queue.dequeue();
queue.display();
}
}
```
这是一个基本的循环队列实现,它包含了常用的操作方法,如入队(enqueue)、出队(dequeue)、判空(isEmpty)、判满(isFull)和显示队列元素(display)。你可以根据需要进行扩展和修改。注意,在入队和出队操作时,使用取模运算(%)来实现循环的效果。
阅读全文