Ai
1 Star 0 Fork 0

CS-IMIS-23/20172306

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
CircularArrayQueue.java 2.17 KB
一键复制 编辑 原始数据 按行查看 历史
20172306 提交于 2018-09-26 22:31 +08:00 . PP5.2
package wek3;
import wek1.EmptyCollectionException;
public class CircularArrayQueue<T> implements QueueADT<T> {
private final static int DEFAULT_CAPACITY = 100;
private int front, rear, count;
private T[] queue;
public CircularArrayQueue(int initialCapacity) {
front = rear = count = 0;
queue = ((T[]) (new Object[initialCapacity]));
}
public CircularArrayQueue() {
this(DEFAULT_CAPACITY);
}
@Override
public void enqueue(T element) {
if (size() == queue.length) {
expandCapacity();
}
queue[rear] = element;
rear = (rear + 1) % queue.length;
count++;
}
/**
* Creates a new array to store the contents of this queue with
* twice the capacity of the old one.
*/
private void expandCapacity() {
T[] larger = (T[]) (new Object[queue.length * 2]);
for (int scan = 0; scan < count; scan++) {
larger[scan] = queue[front];
front = (front + 1) % queue.length;
}
front = 0;
rear = count;
queue = larger;
}
@Override
public T dequeue() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException("queue");
}
T result = queue[front];
queue[rear] = null;
front = (front + 1) % queue.length;
count--;
return result;
}
@Override
public T first() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException("wrong");
}
T result = queue[front];
return result;
}
@Override
public int size() {
return rear - front;
}
@Override
public boolean isEmpty() {
if (size() == 0) {
return true;
} else {
return false;
}
}
@Override
public String toString() {
int j = front;//从头开始遍历
String result = "";
for (int i = 0; i < size(); i++) {//逐渐向后遍历
result += queue[j] + " ";
j = (j + 1) % queue.length;//如果到达末端,则索引回0,否则加1继续
}
return result;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/CS-IMIS-23/20172306.git
git@gitee.com:CS-IMIS-23/20172306.git
CS-IMIS-23
20172306
20172306
master

搜索帮助