/**
* 自己实现一个队列
*/
public class MyQueue {
private int[] objs;
//队列的头部,获取数据时,总是从头部获取
private int head;
//队列的尾部,push数据时,总是从尾部添加
private int tail;
//队列的实际长度
private int size;
//队列的最大容量
private int capacity;
//数组的最大下标
private int maxIndex;
public MyQueue(int size) {
this.capacity = size;
this.maxIndex = size - 1;
this.size = 0;
this.objs = new int[size];
this.head = this.tail = -1;
}
//往队尾添加数据
public boolean offer(int i) {
if (size >= capacity) {
return false;
}
if (++tail > maxIndex) {
tail = 0;
}
objs[tail] = i;
size++;
return true;
}
//从队头拉出数据
public int poll() {
Integer i = null;
if (size <= 0) {
return i;
}
if (++head >= capacity) {
head = 0;
}
size--;
int temp = objs[head];
//通过包装类integer将int置空
objs[head] = i;
return temp;
}
//清空队列
public void clear() {
Integer i = null;
for (int j = 0; j < objs.length; j++) {
tail = head = -1;
size = 0;
}
}
}
使用数组手写一个队列
最新推荐文章于 2021-11-02 21:17:08 发布