Stack & Queue
大纲
1. Stack介绍
2. Queue介绍
3. 例题分析
Stack
A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle
Operations: Push O(1), Pop O(1), Top O(1)
栈的用途
可以用 Stack 作为辅助,实现深度优先算法(Depth first search, DFS),或者将递归转为while循环
递归本身就是相当于把函数本身一层一层加到操作系统的内存栈上;入栈操作相当于递归调用自身,出栈操作相当于递归返回。
工具箱:C++
stack and queue:
bool empty() const; // Returns whether the stack is empty: i.e. whether its size is zero. void push (const value_type& val); // Inserts a new element at the top of the stack. The content of this new element is initialized to a copy of val. void pop(); // Removes the element on top of the stack, effectively reducing its size by one. value_type& top(); // Returns a reference to the top element in the stack
Example:
stack<int> myStack; myStack.push(10); myStack.push(20); int value = myStack.top(); // value equals to 20 queue<int> myQueue; myQueue.push(10); myQueue.push(20); // queue now has two elements, the value of which is 10, 20 int value = myQueue.front(); // value equals to 10 myQueue.pop(); // queue now has one element, the value of which is 20
Queue
A queue is a container of objects (a linear collection) that are inserted and removed according to the first-in first-out (FIFO) principle
Operations: O(1) Push,O(1) Pop,O(1) Top
Always used for BFS
用途
我们可以用 Queue 作为辅助,实现广度优先算法(Breadth first search, BFS)
Queue 还可以作为 buffer,构建一个生产者-消费者模型:生产者把新的元素加到队尾,消费者从队头读取元素。在有两个线程同时读取同一个 queue 时,需要考虑同步(synchronization)
stack 与 queue 可以视作封装好的 Linked list,只是限制了访问和插入的自由。适用 stack 或 queue 的情境,也可以考虑使用更为强大的list。
模式识别
1. 通过stack实现特殊顺序的读取由于 stack 具有 LIFO 的特性,如需实现任何特定顺序的读取操作,往往可以借助两个 stack 互相”倾倒"来实现特定顺序。另一个stack作为辅助。
Get Max Stack
Implement a stack, enable O(1) Push, Pop Top, Max. Where Max() will return the value of maximum number in the stack.
解答
Using two stacks.
The first one is the regular stack. The second one only store maximum numbers if a larger number comes.
复杂度分析:时间复杂度符合题目要求为 O(1)。空间复杂度最坏情况附加的 stack 中需要储存每个元素,故额外使用O(n)空间。