|
发表于 2023-11-12 20:10:31
|
显示全部楼层
我们可以根据你的需求创建一个泛型的循环队列类。下面是泛型类CircularQueue的一个基本实现:
- public class CircularQueue<T> {
- private T[] queue;
- private int head;
- private int tail;
- private int size;
- @SuppressWarnings("unchecked")
- public CircularQueue(int capacity) {
- queue = (T[]) new Object[capacity];
- head = 0;
- tail = 0;
- size = 0;
- }
-
- public boolean enqueue(T element) {
- if (size == queue.length) {
- return false; // 队列已满
- }
- queue[tail] = element;
- tail = (tail + 1) % queue.length;
- size++;
- return true;
- }
- public T dequeue() {
- if (size == 0) {
- return null; // 队列为空
- }
- T result = queue[head];
- head = (head + 1) % queue.length;
- size--;
- return result;
- }
- public T getFront() {
- if (size == 0) {
- return null; // 队列为空
- }
- return queue[head];
- }
- public boolean isEmpty() {
- return size == 0;
- }
- public int getSize() {
- return size;
- }
- }
复制代码
这个泛型类包含了以下方法:
- CircularQueue(int capacity): 创建指定容量的循环队列。
- enqueue(T element): 将元素添加到队列末尾,如果队列已满,返回false。
- dequeue(): 从队列头部删除元素并返回,如果队列为空,返回null。
- getFront(): 返回队列头部的元素,如果队列为空,返回null。
- isEmpty(): 判断队列是否为空,如果为空,返回true。
- getSize(): 返回队列中元素的个数。
请注意,这个循环队列的容量是固定的,如果你需要动态扩容的循环队列,需要进行适当的修改。 |
|