阅读量:2
在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()
方法分别用于检查队列是否为空和是否已满。