大部分记录均来自小灰漫画算法
· 区分物理结构和逻辑结构
![](https://img.haomeiwen.com/i11725840/d8567e83f20e0f6c.png)
· 什么是栈
栈是一种线性数据结构;栈中的元素只能先入后出。实现:Stack和LinkedStack
![](https://img.haomeiwen.com/i11725840/07497bca0047430b.png)
· 什么是队列
队列是一种线性数据结构,队列中的元素只能先入先出。队列的出口端叫对头,队列的入口端叫队尾。
为了避免队列的空间维持恒定:
在数组不扩容的前提下,利用已出队元素留下的空间,让队尾指针重新指挥数组的首位。一直到队尾下标+1 % 数组长度 = 对头下标。需要注意的是,这种做法需要队尾指针指向的位置永远空出1位,所以队列最大容量比数组长度小1。
public class MyQueue {
//恒定数组
private int [] array;
//队头
private int front;
//队尾
private int end;
public MyQueue(int capacity) {
this.array = new int[capacity];
}
public int deQueue() throws Exception {
if(end == front) {
throw new Exception("队列以空");
}
int deQueueElement = array[front];
front = (front + 1) % array.length;
return deQueueElement;
}
public void enQueue(int element) throws Exception{
if((end + 1) % array.length == front) {
throw new Exception("队列已满");
}
array[end] = element;
end = (end + 1) % array.length;
}
}
· 各自的应用
栈通常用于对“历史”的回溯。
队列通常用于对“历史”的回放。重现之前的操作步骤。
双端队列同时实现了栈和队列的优点。
网友评论