刷题总结 - Queue & Stack
We may access a random element by index in Array
. However, we might want to restrict the processing order in some cases.
In this card, we introduce two different processing orders, First-in-First-out and Last-in-First-out and its two corresponding linear data structures, Queue
and Stack
.
We go through the definition, implementation and built-in functions for each data structure. Then, we focus more on the practical applications of these two data structures.
By completing this card, you should be able to:
- Understand the principle of the processing orders of
FIFO
andLIFO
; - Implement these two data structures;
- Be familiar with the built-in queue and stack structure;
- Solve basic queue-related problems, especially
BFS
; - Solve basic stack-related problems problems;
- Understand how system stack helps you when you solve problems using
DFS
and other recursion algorithms;
First-in-first-out Data Structure
In a FIFO data structure, the first element added to the queue will be processed first.
As shown in the picture above, the queue is a typical FIFO data stucture. The insert operation is also called enqueue and the new element is always added at the end of the queue. The delete operation is called dequeue. You are only allowed to remove the first element.
Example - Queue
- Enqueue:
- Dequeue:
Queue - Implementation
To implement a queue, we may use a dynamic array
and an index pointing to the head of the queue.
As mentioned, a queue should support two operations: enqueue
and dequeue
. Enqueue appends a new element to the queue while dequeue removes the first element. So we need an index to indicate the starting point.
Here is an implementation for your reference:
1 | // "static void main" must be defined in a public class. |
Drawback
The implementation above is straightforward but is inefficient in some cases. With the movement of the start pointer, more and more space is wasted. And it will be unacceptable when we only have a space limitation.
Let's consider a situation when we are only able to allocate an array whose maximum length is 5. Our solution works well when we have only added less than 5 elements. For example, if we only called the enqueue function four times and we want to enqueue an element 10, we will succeed.
And it is reasonable that we can not accept more enqueue request because the queue is full now. But what if we dequeue an element?
Actually, we should be able to accept one more element in this case.
Circular Queue
Previously, we have provided a straightforward but inefficient implementation of queue.
A more efficient way is to use a circular queue. Specifically, we may use a fixed-size array and two pointers to indicate the starting position and the ending position. And the goal is to reuse the wasted storage we mentioned previously.
Let's take a look at an example to see how a circular queue works. You should pay attention to the strategy we use to enqueue
or dequeue
an element.
Review the animation carefully to figure out the strategy we use to check if a queue is empty
or full
.
For the next exercise, we will let you try to implement the circular queue by yourself and provide a solution later.
In a circular queue
, we use an array and two pointers, head and tail. head indicates the start position of the queue while tail indicates the ending position of the queue.
1 | 思路:看到 circular 自然联想到用 % 来解决问题。 |
Queue - Usage
Most popular languages provide built-in Queue library so you don't have to reinvent the wheel.
As mentioned before, the queue has two important operations, enqueue
and dequeue
. Besides, we should be able to get the first element
in a queue since the first element should be processed first.
Below are some examples of using the built-in Queue library and its common operations:
1 | 1. Queue 用 LinkedList 实现。 |
Throws exception | Returns special value | |
---|---|---|
Insert | add(e) | offer(e) |
Remove | remove() | poll() |
Examine | element() | peek() |
The remove()
and poll()
methods remove and return the head of the queue. Exactly which element is removed from the queue is a function of the queue's ordering policy, which differs from implementation to implementation. The remove()
and poll()
methods differ only in their behavior when the queue is empty: the remove()
method throws an exception, while the poll()
method returns null
.
Question - Moving Average from Data Stream
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
1 | MovingAverage m = new MovingAverage(3); |
1 | public class MovingAverage { |
Queue and BFS
One common application of Breadth-first Search (BFS) is to find the shortest path from the root node to the target node. In this article, we provide an example to explain how queue is applied in a BFS algorithm step by step.
Insights
After watching the animation above, let's answer the following questions:
1. What is the processing order of the nodes?
In the first round, we process the root node. In the second round, we process the nodes next to the root node; in the third round, we process the nodes which are two steps from the root node; so on and so forth.
Similar to tree's level-order traversal, the nodes closer to the root node will be traversed earlier.
If a node X
is added to the queue in the kth
round, the length of the shortest path between the root node and X
is exactly k
. That is to say, you are already in the shortest path the first time you find the target node.
2. What is the enqueue and dequeue order of the queue?
As shown in the animation above, we first enqueue the root node. Then in each round, we process the nodes which are already in the queue one by one and add all their neighbors to the queue. It is worth noting that the newly-added nodes will not be traversed immediately but will be processed in the next round.
The processing order of the nodes is the exact same order as how they were added to the queue, which is First-in-First-out (FIFO). That's why we use a queue in BFS.