在Java中,可以使用數組和指針來實現循環隊列。以下是一個簡單的循環隊列的實現示例:
public class CircularQueue {
private int[] queue;
private int front;
private int rear;
private int size;
private int capacity;
public CircularQueue(int capacity) {
this.capacity = capacity;
queue = new int[capacity];
front = 0;
rear = -1;
size = 0;
}
public void enqueue(int item) {
if (isFull()) {
System.out.println("Queue is full");
return;
}
rear = (rear + 1) % capacity;
queue[rear] = item;
size++;
}
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty");
return -1;
}
int item = queue[front];
front = (front + 1) % capacity;
size--;
return item;
}
public int front() {
if (isEmpty()) {
System.out.println("Queue is empty");
return -1;
}
return queue[front];
}
public int rear() {
if (isEmpty()) {
System.out.println("Queue is empty");
return -1;
}
return queue[rear];
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
}
使用示例:
public class Main {
public static void main(String[] args) {
CircularQueue queue = new CircularQueue(5);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println(queue.front()); // Output: 1
System.out.println(queue.rear()); // Output: 3
queue.dequeue();
System.out.println(queue.front()); // Output: 2
System.out.println(queue.isFull()); // Output: false
}
}
在以上示例中,CircularQueue
類中的 enqueue()
方法用于向隊列中添加元素,dequeue()
方法用于從隊列中刪除元素,front()
和 rear()
方法用于返回隊列的第一個元素和最后一個元素。isEmpty()
和 isFull()
方法分別用于檢查隊列是否為空和是否已滿。