1. 前言
上文我们用环形单向链表实现了队列.接下来我们用环形数组来模拟队列.并实现了isFull(),isEmpty()等方法.
2. 环形数组模拟队列
(1). Queue接口 :
public interface Queue<E> { //向队伍插入值, 插入成功返回true, 否则返回false boolean 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]; } @Override public boolean offer(E value) { //如果队伍已经满了, 那么添加元素失败 if(isFull()) { return false; } queue[tail] = value; tail = (tail + 1) % queue.length; return true; } @Override public E poll() { //如果队列为空, 那么返回null if(isEmpty()) { return null; } return queue[head]; } @Override public E peek() { //如果队列为空, 那么返回null E value = queue[head]; head = (head + 1) % queue.length; return value; } @Override public boolean isEmpty() { return head == tail; } @Override public boolean isFull() { //数组的长度queue.length并不等于数组的容量capacity return (tail+1) % queue.length == head; } @Override public Iterator<E> iterator() { return new Iterator<E>() { int p = head; @Override public boolean hasNext() { return p != tail; } @Override public E next() { E value = queue[p]; p++; return value; } }; } }
3. 单元测试
public class ArrayQueueTest { @Test public 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); // } //12345 System.out.println(queue.poll()); //1 System.out.println(queue.peek()); //1 System.out.println(queue.poll()); //2 } }