第三章 栈和队列
3-5 数组队列
3-6 循环队列
3-7 循环队列的实现
3-8 数组队列和循环队列的比较
3-5 数组队列
队列(Queue)也是一种线性结构。相比数组,队列对应的操作是数组的子集,队列只能从一端(队尾)添加元素,只能从另一段(队首)取出元素。因此我们说队列是一种先进先出的数据结构(先到先得)First In First Out (FIFO)
举个栗子:去超市排队结账时,小兔、小猪、小象买好东西正在依次排队,小老虎刚买好,准备去排队。那么小老虎是排在小象后边,并且一定是小兔、小猪、小象、小老虎这样的顺序离开超市。不然要打架的。
队列的实现Queue< E >涉及以下几个基本操作:
- void enqueue (E):向队列队尾中添加元素(入队)—> O(1) 均摊
- E dequeue ( ):从队列队首中取出元素(出队)—> O(n)
(这里,对于出队操作:每一次将第一个数组的元素即索引为0的元素取出后,数组中剩下的元素都要向前挪一个位置,因此这个操作的复杂度为O(n)) - E getFront ( ):查看队首元素 —> O(1)
- int getSize ( ):获取队列中元素的个数 —> O(1)
- boolean isEmpty ( ):判断队列是否为空 —> O(1)
以下为数组队列相关的代码实现,和上一章节相近:
public interface Queue<E> {
int getSize();
boolean isEmpty();
void enqueue(E e);
E dequeue();
E getFront();
}
基于对象多态性的理念,在代码设计上设计一个Queue< E >的接口,并在接口中定义以上五种方法。在实现数组Array的条件下,设计一个ArrayQueue< E >的类,实际上是实现了Queue< E >的接口后,具体完成了接口中相应的方法逻辑。实现代码如下:
public class ArrayQueue<E> implements Queue<E> {
private Array<E> array;
public ArrayQueue(int capacity){
array = new Array<E>(capacity);
}
public ArrayQueue(){
array = new Array<E>();
}
@Override
public int getSize(){
return array.getSize();
}
@Override
public boolean isEmpty(){
return array.isEmpty();
}
public int getCapacity(){
return array.getCapacity();
}
@Override
public void enqueue(E e){
array.addLast(e);
}
@Override
public E dequeue(){
return array.removeFirst();
}
@Override
public E getFront(){
return array.getFirst();
}
@Override //覆盖父类的方法
public String toString(){
StringBuilder res = new StringBuilder();
res.append("Queue:");
res.append("front [");
for (int i = 0; i < array.getSize(); i++){
res.append(array.get(i));
if (i != array.getSize() - 1)
res.append(", ");
}
res.append("] tail");
return res.toString();
}
}
以上我们已经实现了一个数组队列,接下来在Main方法中测试一下数组队列,其中if (i % 3 == 2)表示“每插入队列三个元素,就取出一个元素”:
public class Main {
public static void main(String[] args){
// ArrayQueue: 数组队列
ArrayQueue<Integer> queue = new ArrayQueue<>();
for (int i = 0; i < 10; i ++){
queue.enqueue(i);
System.out.println(queue);
if (i % 3 == 2){
// 每插入队列三个元素,就取出一个元素
queue.dequeue();
System.out.println(queue);
}
}
}
}
运行的结果如下:
Queue:front [0] tail
Queue:front [0, 1] tail
Queue:front [0, 1, 2] tail
Queue:front [1, 2] tail
Queue:front [1, 2, 3] tail
Queue:front [1, 2, 3, 4] tail
Queue:front [1, 2, 3, 4, 5] tail
Queue:front [2, 3, 4, 5] tail
Queue:front [2, 3, 4, 5, 6] tail
Queue:front [2, 3, 4, 5, 6, 7] tail
Queue:front [2, 3, 4, 5, 6, 7, 8] tail
Queue:front [3, 4, 5, 6, 7, 8] tail
Queue:front [3, 4, 5, 6, 7, 8, 9] tail
3-6 & 3-7 循环队列及其实现
上一章节数组队列具有局限性,关键问题在于“出队”这个操作具有O(n)的复杂度。解决方法:循环队列
循环队列以front指向队首,以tail指向队尾之后一位
初始情况队列为空:front和tail都指向0
front = = tail : 队列为空
进行入队操作时, tail向后移动一位;
进行出队操作时,front向后移动一位;
当tail指向的位置超出队列时(即tail的索引指向最大capacity时),可复用队列前,由于出队操作而空余出的空间
- 这里也可以将循环队列看作一个环,每个环有其对应的索引值;改变索引的值,实现循环队列。
- 数组可以利用前面已经释放的空间,此时capacity 有意地浪费一个空间。
(tail + 1) % capacity = = front : 队列满
这里需要说明一下:因为front == tail:队列为空,队列满的时候再加一个元素会导致front = = tail,因此我们浪费一个空间,来表示队列满的状态。
这里想说一下,循环数列的还是很重要的,难度也比上面的数组队列多一些,不能一下子就理解的话,可以画画图,加深一下了解。循环数列的实现代码如下:
public class LoopQueue<E> implements Queue<E> {
private E[] data;
private int front, tail;
private int size;
public LoopQueue(int capacity){
data = (E[]) new Object[capacity + 1];
front = 0;
tail = 0;
size = 0;
}
public LoopQueue(){
this(10);
}
public int getCapacity(){
return data.length - 1;
}
@Override
public boolean isEmpty(){
return front == tail;
}
@Override
public int getSize(){
return size;
}
// 入队操作(重点部分)
@Override
public void enqueue(E e){
if ((tail + 1) % data.length == front)
resize(getCapacity() * 2);
data[tail] = e;
tail = (tail + 1) % data.length;
size ++;
}
//出队操作(重点部分)
public E dequeue(){
if (isEmpty())
throw new IllegalArgumentException("Cannot dequeue from an empty queue.");
E ret = data[front];
data[front] = null;
front = (front + 1) % data.length;
size --;
// 这里是一个缩容操作
if (size == getCapacity() / 4 && getCapacity() / 2 != 0)
resize(getCapacity() / 2);
return ret;
}
@Override
public E getFront(){
if (isEmpty())
throw new IllegalArgumentException("Queue is empty.");
return data[front];
}
// resize这里也改变了,多看几遍自行体会
private void resize(int newCapacity){
E[] newData = (E[]) new Object[newCapacity + 1];
for (int i = 0; i < size; i ++)
newData[i] = data[(i + front) % data.length];
data = newData;
front = 0;
tail = size;
}
@Override //覆盖父类的方法
public String toString(){
StringBuilder res = new StringBuilder();
res.append(String.format("Queue: size = %d, capacity = %d\n", size, getCapacity()));
res.append("front [");
for (int i = front; i != tail; i = (i + 1) % data.length){
res.append(data[i]);
if ((i + 1) % data.length != tail)
res.append(", ");
}
res.append("] tail");
return res.toString();
}
}
以上我们已经实现了一个数组队列,接下来在Main方法中测试一下数组队列,其中if (i % 3 == 2)表示“每插入队列三个元素,就取出一个元素”:
public class Main {
public static void main(String[] args){
// LoopQueue:循环队列
LoopQueue<Integer> queue = new LoopQueue<>();
for (int i = 0; i < 10; i++) {
queue.enqueue(i);
System.out.println(queue);
if (i % 3 == 2) {
// 每插入队列三个元素,就取出一个元素
queue.dequeue();
System.out.println(queue);
}
}
}
}
运行结果如下:
Queue: size = 1, capacity = 10
front [0] tail
Queue: size = 2, capacity = 10
front [0, 1] tail
Queue: size = 3, capacity = 10
front [0, 1, 2] tail
Queue: size = 2, capacity = 5
front [1, 2] tail
Queue: size = 3, capacity = 5
front [1, 2, 3] tail
Queue: size = 4, capacity = 5
front [1, 2, 3, 4] tail
Queue: size = 5, capacity = 5
front [1, 2, 3, 4, 5] tail
Queue: size = 4, capacity = 5
front [2, 3, 4, 5] tail
Queue: size = 5, capacity = 5
front [2, 3, 4, 5, 6] tail
Queue: size = 6, capacity = 10
front [2, 3, 4, 5, 6, 7] tail
Queue: size = 7, capacity = 10
front [2, 3, 4, 5, 6, 7, 8] tail
Queue: size = 6, capacity = 10
front [3, 4, 5, 6, 7, 8] tail
Queue: size = 7, capacity = 10
front [3, 4, 5, 6, 7, 8, 9] tail
3-8 数组队列和循环队列的比较
循环队列的复杂度分析 LoopQueue< E >:
- void enqueue (E):向队列队尾中添加元素(入队)—> O(1) 均摊
- E dequeue ( ):从队列队首中取出元素(出队)—> O(1) 均摊
- E getFront ( ):查看队首元素 —> O(1)
- int getSize ( ):获取队列中元素的个数 —> O(1)
- boolean isEmpty ( ):判断队列是否为空 —> O(1)
循环队列将维护的对象从数组中的元素,改成了front 和 tail,使得enqueue和dequeue操作的时间复杂度降低到了O(1),扩容和缩容的时候用均摊复杂度的分析方法。
用代码测试两个队列有什么不同:
import java.util.Random;
public class Main {
//测试使用q云顶opCount个enqueue和dequeue操作所需要的时间,单位:秒
private static double testQueue(Queue<Integer> q, int opCount){
long startTime = System.nanoTime();
Random random = new Random();
for (int i = 0; i < opCount; i ++)
q.enqueue(random.nextInt(Integer.MAX_VALUE));
for (int i = 0; i < opCount; i ++)
q.dequeue();
long endTime = System.nanoTime();
return (endTime - startTime) / 1000000000.0; //纳秒=>秒,10^9
}
public static void main(String[] args){
int opCount = 100000;
ArrayQueue<Integer> arrayQueue = new ArrayQueue<>();
double time1 = testQueue(arrayQueue, opCount);
System.out.println("ArrayQueue, time: " + time1 + " s");
LoopQueue<Integer> loopQueue = new LoopQueue<>();
double time2 = testQueue(loopQueue, opCount);
System.out.println("LoopQueue, time: " + time2 + " s");
}
}
运行结果如下:
ArrayQueue, time: 25.141221072 s
LoopQueue, time: 0.013766594 s
(这就是我们算法为什么要提升算法性能,降低算法复杂度)