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 data) {
if (isFull()) {
throw new IllegalStateException("Queue is full");
}
rear = (rear + 1) % queue.length;
queue[rear] = data;
size++;
}
public int dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
int data = queue[front];
front = (front + 1) % queue.length;
size--;
return data;
}
}
public class CircularQueue {
private static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
private Node head;
private Node tail;
private int size;
public CircularQueue() {
head = null;
tail = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public void enqueue(int data) {
Node newNode = new Node(data);
if (isEmpty()) {
head = newNode;
} else {
tail.next = newNode;
}
tail = newNode;
tail.next = head; // make it circular
size++;
}
public int dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
int data = head.data;
if (head == tail) { // only one node in the queue
head = null;
tail = null;
} else {
head = head.next;
tail.next = head; // remove the reference to the old head node
}
size--;
return data;
}
}
以上是兩種常見的循環隊列的實現方式,可以根據自己的實際需求選擇適合的實現方式。