1. 前言
上文我们用环形单向链表实现了队列.接下来我们用环形数组来模拟队列.并实现了isFull(),isEmpty()等方法.
2. 环形数组模拟队列
(1). Queue接口 :
public interface Queue<E> {//向队伍插入值, 插入成功返回true, 否则返回falseboolean offer(E value);//对队头获取值, 但不移除E poll();//从队头获取值, 并移除队头E peek();//判断队伍是否为空boolean isEmpty();//判断队列是否已满boolean isFull();
}
(2). 环形数组模拟队列
public class ArrayQueue<E> implements Queue<E>, Iterable<E>{//数组的容量private int capacity;//环形数组private E[] queue;//队头private int head = 0;//队尾private int tail = 0;public ArrayQueue() {capacity = 10;}public ArrayQueue(int capacity) {this.capacity = capacity;//数组capacity个位置存储数据, 剩下一个位置用来区分队伍是满了还是空了的情况queue = (E[]) new Object[capacity + 1];}@Overridepublic boolean offer(E value) {//如果队伍已经满了, 那么添加元素失败if(isFull()) {return false;}queue[tail] = value;tail = (tail + 1) % queue.length;return true;
}@Overridepublic E poll() {//如果队列为空, 那么返回nullif(isEmpty()) {return null;}return queue[head];}@Overridepublic E peek() {//如果队列为空, 那么返回nullE value = queue[head];head = (head + 1) % queue.length;return value;}@Overridepublic boolean isEmpty() {return head == tail;}@Overridepublic boolean isFull() {//数组的长度queue.length并不等于数组的容量capacityreturn (tail+1) % queue.length == head;}@Overridepublic Iterator<E> iterator() {return new Iterator<E>() {int p = head;@Overridepublic boolean hasNext() {return p != tail;}@Overridepublic E next() {E value = queue[p];p++;return value;}};}
}
3. 单元测试
public class ArrayQueueTest {@Testpublic void test() {ArrayQueue<Integer> queue = new ArrayQueue<>(5);queue.offer(1);queue.offer(2);queue.offer(3);queue.offer(4);queue.offer(5);
// for (Integer element : queue) {
// System.out.print(element);
// }//12345System.out.println(queue.poll());//1System.out.println(queue.peek());//1System.out.println(queue.poll());//2}
}