Retranslate the complete English edition from Simplified Chinese (#2010)

* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
This commit is contained in:
Yudong Jin
2026-10-31 03:35:51 +08:00
committed by GitHub
parent ef46e2ed95
commit 14c314c08c
1502 changed files with 29459 additions and 23517 deletions

View File

@@ -1,39 +1,39 @@
# Deque
# Deques
In a queue, we can only remove elements from the front or add elements at the rear. As shown in the figure below, a <u>double-ended queue (deque)</u> provides greater flexibility, allowing elements to be added or removed at both the front and the rear.
A queue allows removal only at the front and insertion only at the rear. As shown below, a <u>double-ended queue</u>, or deque, is more flexible: elements can be added or removed at either end.
![Operations of deque](deque.assets/deque_operations.png)
![Deque operations](deque.assets/deque_operations.png)
## Common Deque Operations
## Common deque operations
The common operations on a deque are shown in the table below. The specific method names depend on the programming language used.
The table below lists common operations. Actual method names depend on the programming language.
<p align="center"> Table <id> &nbsp; Efficiency of Deque Operations </p>
<p align="center"> Table <id> &nbsp; Efficiency of deque operations </p>
| Method | Description | Time Complexity |
| -------------- | ------------------------- | --------------- |
| `push_first()` | Add element to front | $O(1)$ |
| `push_last()` | Add element to rear | $O(1)$ |
| `pop_first()` | Remove front element | $O(1)$ |
| `pop_last()` | Remove rear element | $O(1)$ |
| `peek_first()` | Access front element | $O(1)$ |
| `peek_last()` | Access rear element | $O(1)$ |
| Method | Description | Time complexity |
| -------------- | ---------------- | ---------- |
| `push_first()` | Add an element at the front | $O(1)$ |
| `push_last()` | Add an element at the rear | $O(1)$ |
| `pop_first()` | Remove the front element | $O(1)$ |
| `pop_last()` | Remove the rear element | $O(1)$ |
| `peek_first()` | Access the front element | $O(1)$ |
| `peek_last()` | Access the rear element | $O(1)$ |
Similarly, we can directly use the deque classes provided by the programming language:
Again, we can use a deque class already provided by the programming language:
=== "Python"
```python title="deque.py"
from collections import deque
# Initialize deque
# Initialize a deque
deq: deque[int] = deque()
# Enqueue elements
deq.append(2) # Add to rear
deq.append(2) # Add at the rear
deq.append(5)
deq.append(4)
deq.appendleft(3) # Add to front
deq.appendleft(3) # Add at the front
deq.appendleft(1)
# Access elements
@@ -41,27 +41,27 @@ Similarly, we can directly use the deque classes provided by the programming lan
rear: int = deq[-1] # Rear element
# Dequeue elements
pop_front: int = deq.popleft() # Front element dequeue
pop_rear: int = deq.pop() # Rear element dequeue
pop_front: int = deq.popleft() # Remove the front element
pop_rear: int = deq.pop() # Remove the rear element
# Get deque length
# Get the deque size
size: int = len(deq)
# Check if deque is empty
# Check whether the deque is empty
is_empty: bool = len(deq) == 0
```
=== "C++"
```cpp title="deque.cpp"
/* Initialize deque */
/* Initialize a deque */
deque<int> deque;
/* Enqueue elements */
deque.push_back(2); // Add to rear
deque.push_back(2); // Add at the rear
deque.push_back(5);
deque.push_back(4);
deque.push_front(3); // Add to front
deque.push_front(3); // Add at the front
deque.push_front(1);
/* Access elements */
@@ -69,27 +69,27 @@ Similarly, we can directly use the deque classes provided by the programming lan
int back = deque.back(); // Rear element
/* Dequeue elements */
deque.pop_front(); // Front element dequeue
deque.pop_back(); // Rear element dequeue
deque.pop_front(); // Remove the front element
deque.pop_back(); // Remove the rear element
/* Get deque length */
/* Get the deque size */
int size = deque.size();
/* Check if deque is empty */
/* Check whether the deque is empty */
bool empty = deque.empty();
```
=== "Java"
```java title="deque.java"
/* Initialize deque */
/* Initialize a deque */
Deque<Integer> deque = new LinkedList<>();
/* Enqueue elements */
deque.offerLast(2); // Add to rear
deque.offerLast(2); // Add at the rear
deque.offerLast(5);
deque.offerLast(4);
deque.offerFirst(3); // Add to front
deque.offerFirst(3); // Add at the front
deque.offerFirst(1);
/* Access elements */
@@ -97,28 +97,28 @@ Similarly, we can directly use the deque classes provided by the programming lan
int peekLast = deque.peekLast(); // Rear element
/* Dequeue elements */
int popFirst = deque.pollFirst(); // Front element dequeue
int popLast = deque.pollLast(); // Rear element dequeue
int popFirst = deque.pollFirst(); // Remove the front element
int popLast = deque.pollLast(); // Remove the rear element
/* Get deque length */
/* Get the deque size */
int size = deque.size();
/* Check if deque is empty */
/* Check whether the deque is empty */
boolean isEmpty = deque.isEmpty();
```
=== "C#"
```csharp title="deque.cs"
/* Initialize deque */
// In C#, use LinkedList as a deque
/* Initialize a deque */
// In C#, use a LinkedList as a deque
LinkedList<int> deque = new();
/* Enqueue elements */
deque.AddLast(2); // Add to rear
deque.AddLast(2); // Add at the rear
deque.AddLast(5);
deque.AddLast(4);
deque.AddFirst(3); // Add to front
deque.AddFirst(3); // Add at the front
deque.AddFirst(1);
/* Access elements */
@@ -126,28 +126,28 @@ Similarly, we can directly use the deque classes provided by the programming lan
int peekLast = deque.Last.Value; // Rear element
/* Dequeue elements */
deque.RemoveFirst(); // Front element dequeue
deque.RemoveLast(); // Rear element dequeue
deque.RemoveFirst(); // Remove the front element
deque.RemoveLast(); // Remove the rear element
/* Get deque length */
/* Get the deque size */
int size = deque.Count;
/* Check if deque is empty */
/* Check whether the deque is empty */
bool isEmpty = deque.Count == 0;
```
=== "Go"
```go title="deque_test.go"
/* Initialize deque */
// In Go, use list as a deque
/* Initialize a deque */
// In Go, use a list as a deque
deque := list.New()
/* Enqueue elements */
deque.PushBack(2) // Add to rear
deque.PushBack(2) // Add at the rear
deque.PushBack(5)
deque.PushBack(4)
deque.PushFront(3) // Add to front
deque.PushFront(3) // Add at the front
deque.PushFront(1)
/* Access elements */
@@ -155,28 +155,28 @@ Similarly, we can directly use the deque classes provided by the programming lan
rear := deque.Back() // Rear element
/* Dequeue elements */
deque.Remove(front) // Front element dequeue
deque.Remove(rear) // Rear element dequeue
deque.Remove(front) // Remove the front element
deque.Remove(rear) // Remove the rear element
/* Get deque length */
/* Get the deque size */
size := deque.Len()
/* Check if deque is empty */
/* Check whether the deque is empty */
isEmpty := deque.Len() == 0
```
=== "Swift"
```swift title="deque.swift"
/* Initialize deque */
// Swift does not have a built-in deque class, can use Array as a deque
/* Initialize a deque */
// Swift has no built-in deque class; use an Array as a deque
var deque: [Int] = []
/* Enqueue elements */
deque.append(2) // Add to rear
deque.append(2) // Add at the rear
deque.append(5)
deque.append(4)
deque.insert(3, at: 0) // Add to front
deque.insert(3, at: 0) // Add at the front
deque.insert(1, at: 0)
/* Access elements */
@@ -184,29 +184,29 @@ Similarly, we can directly use the deque classes provided by the programming lan
let peekLast = deque.last! // Rear element
/* Dequeue elements */
// When using Array simulation, popFirst has O(n) complexity
let popFirst = deque.removeFirst() // Front element dequeue
let popLast = deque.removeLast() // Rear element dequeue
// When using an Array, popFirst takes O(n) time
let popFirst = deque.removeFirst() // Remove the front element
let popLast = deque.removeLast() // Remove the rear element
/* Get deque length */
/* Get the deque size */
let size = deque.count
/* Check if deque is empty */
/* Check whether the deque is empty */
let isEmpty = deque.isEmpty
```
=== "JS"
```javascript title="deque.js"
/* Initialize deque */
// JavaScript does not have a built-in deque, can only use Array as a deque
/* Initialize a deque */
// JavaScript has no built-in deque; use an Array instead
const deque = [];
/* Enqueue elements */
deque.push(2);
deque.push(5);
deque.push(4);
// Please note that since it's an array, unshift() has O(n) time complexity
// Note that this is an array, so unshift() takes O(n) time
deque.unshift(3);
deque.unshift(1);
@@ -215,29 +215,29 @@ Similarly, we can directly use the deque classes provided by the programming lan
const peekLast = deque[deque.length - 1];
/* Dequeue elements */
// Please note that since it's an array, shift() has O(n) time complexity
// Note that this is an array, so shift() takes O(n) time
const popFront = deque.shift();
const popBack = deque.pop();
/* Get deque length */
/* Get the deque size */
const size = deque.length;
/* Check if deque is empty */
/* Check whether the deque is empty */
const isEmpty = size === 0;
```
=== "TS"
```typescript title="deque.ts"
/* Initialize deque */
// TypeScript does not have a built-in deque, can only use Array as a deque
/* Initialize a deque */
// TypeScript has no built-in deque; use an Array instead
const deque: number[] = [];
/* Enqueue elements */
deque.push(2);
deque.push(5);
deque.push(4);
// Please note that since it's an array, unshift() has O(n) time complexity
// Note that this is an array, so unshift() takes O(n) time
deque.unshift(3);
deque.unshift(1);
@@ -246,29 +246,29 @@ Similarly, we can directly use the deque classes provided by the programming lan
const peekLast: number = deque[deque.length - 1];
/* Dequeue elements */
// Please note that since it's an array, shift() has O(n) time complexity
// Note that this is an array, so shift() takes O(n) time
const popFront: number = deque.shift() as number;
const popBack: number = deque.pop() as number;
/* Get deque length */
/* Get the deque size */
const size: number = deque.length;
/* Check if deque is empty */
/* Check whether the deque is empty */
const isEmpty: boolean = size === 0;
```
=== "Dart"
```dart title="deque.dart"
/* Initialize deque */
/* Initialize a deque */
// In Dart, Queue is defined as a deque
Queue<int> deque = Queue<int>();
/* Enqueue elements */
deque.addLast(2); // Add to rear
deque.addLast(2); // Add at the rear
deque.addLast(5);
deque.addLast(4);
deque.addFirst(3); // Add to front
deque.addFirst(3); // Add at the front
deque.addFirst(1);
/* Access elements */
@@ -276,27 +276,27 @@ Similarly, we can directly use the deque classes provided by the programming lan
int peekLast = deque.last; // Rear element
/* Dequeue elements */
int popFirst = deque.removeFirst(); // Front element dequeue
int popLast = deque.removeLast(); // Rear element dequeue
int popFirst = deque.removeFirst(); // Remove the front element
int popLast = deque.removeLast(); // Remove the rear element
/* Get deque length */
/* Get the deque size */
int size = deque.length;
/* Check if deque is empty */
/* Check whether the deque is empty */
bool isEmpty = deque.isEmpty;
```
=== "Rust"
```rust title="deque.rs"
/* Initialize deque */
/* Initialize a deque */
let mut deque: VecDeque<u32> = VecDeque::new();
/* Enqueue elements */
deque.push_back(2); // Add to rear
deque.push_back(2); // Add at the rear
deque.push_back(5);
deque.push_back(4);
deque.push_front(3); // Add to front
deque.push_front(3); // Add at the front
deque.push_front(1);
/* Access elements */
@@ -306,35 +306,35 @@ Similarly, we can directly use the deque classes provided by the programming lan
}
/* Dequeue elements */
if let Some(pop_front) = deque.pop_front() { // Front element dequeue
if let Some(pop_front) = deque.pop_front() { // Remove the front element
}
if let Some(pop_rear) = deque.pop_back() { // Rear element dequeue
if let Some(pop_rear) = deque.pop_back() { // Remove the rear element
}
/* Get deque length */
/* Get the deque size */
let size = deque.len();
/* Check if deque is empty */
/* Check whether the deque is empty */
let is_empty = deque.is_empty();
```
=== "C"
```c title="deque.c"
// C does not provide a built-in deque
// C provides no built-in deque
```
=== "Kotlin"
```kotlin title="deque.kt"
/* Initialize deque */
/* Initialize a deque */
val deque = LinkedList<Int>()
/* Enqueue elements */
deque.offerLast(2) // Add to rear
deque.offerLast(2) // Add at the rear
deque.offerLast(5)
deque.offerLast(4)
deque.offerFirst(3) // Add to front
deque.offerFirst(3) // Add at the front
deque.offerFirst(1)
/* Access elements */
@@ -342,28 +342,28 @@ Similarly, we can directly use the deque classes provided by the programming lan
val peekLast = deque.peekLast() // Rear element
/* Dequeue elements */
val popFirst = deque.pollFirst() // Front element dequeue
val popLast = deque.pollLast() // Rear element dequeue
val popFirst = deque.pollFirst() // Remove the front element
val popLast = deque.pollLast() // Remove the rear element
/* Get deque length */
/* Get the deque size */
val size = deque.size
/* Check if deque is empty */
/* Check whether the deque is empty */
val isEmpty = deque.isEmpty()
```
=== "Ruby"
```ruby title="deque.rb"
# Initialize deque
# Ruby does not have a built-in deque, can only use Array as a deque
# Initialize a deque
# Ruby has no built-in deque; use an Array instead
deque = []
# Enqueue elements
deque << 2
deque << 5
deque << 4
# Please note that since it's an array, Array#unshift has O(n) time complexity
# Note that this is an array, so Array#unshift takes O(n) time
deque.unshift(3)
deque.unshift(1)
@@ -372,35 +372,35 @@ Similarly, we can directly use the deque classes provided by the programming lan
peek_last = deque.last
# Dequeue elements
# Please note that since it's an array, Array#shift has O(n) time complexity
# Note that this is an array, so Array#shift takes O(n) time
pop_front = deque.shift
pop_back = deque.pop
# Get deque length
# Get the deque size
size = deque.length
# Check if deque is empty
# Check whether the deque is empty
is_empty = size.zero?
```
??? pythontutor "Code Visualization"
??? pythontutor "Visualize execution"
https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E9%98%9F%0A%20%20%20%20deq.append%282%29%20%20%23%20%E6%B7%BB%E5%8A%A0%E8%87%B3%E9%98%9F%E5%B0%BE%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20%E6%B7%BB%E5%8A%A0%E8%87%B3%E9%98%9F%E9%A6%96%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%20deque%20%3D%22,%20deq%29%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E5%85%83%E7%B4%A0%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%20front%20%3D%22,%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20%E9%98%9F%E5%B0%BE%E5%85%83%E7%B4%A0%0A%20%20%20%20print%28%22%E9%98%9F%E5%B0%BE%E5%85%83%E7%B4%A0%20rear%20%3D%22,%20rear%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%87%BA%E9%98%9F%E5%85%83%E7%B4%A0%20%20pop_front%20%3D%22,%20pop_front%29%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%87%BA%E9%98%9F%E5%90%8E%20deque%20%3D%22,%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20%E9%98%9F%E5%B0%BE%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20print%28%22%E9%98%9F%E5%B0%BE%E5%87%BA%E9%98%9F%E5%85%83%E7%B4%A0%20%20pop_rear%20%3D%22,%20pop_rear%29%0A%20%20%20%20print%28%22%E9%98%9F%E5%B0%BE%E5%87%BA%E9%98%9F%E5%90%8E%20deque%20%3D%22,%20deq%29%0A%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E7%9A%84%E9%95%BF%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E9%95%BF%E5%BA%A6%20size%20%3D%22,%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%20%3D%22,%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20deque%0A%20%20%20%20deq%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20Enqueue%20elements%0A%20%20%20%20deq.append%282%29%20%20%23%20Add%20at%20the%20rear%0A%20%20%20%20deq.append%285%29%0A%20%20%20%20deq.append%284%29%0A%20%20%20%20deq.appendleft%283%29%20%20%23%20Add%20at%20the%20front%0A%20%20%20%20deq.appendleft%281%29%0A%20%20%20%20print%28%22Deque%3A%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20Access%20elements%0A%20%20%20%20front%20%3D%20deq%5B0%5D%20%20%23%20Front%20element%0A%20%20%20%20print%28%22Front%20element%3A%20front%20%3D%22%2C%20front%29%0A%20%20%20%20rear%20%3D%20deq%5B-1%5D%20%20%23%20Rear%20element%0A%20%20%20%20print%28%22Rear%20element%3A%20rear%20%3D%22%2C%20rear%29%0A%0A%20%20%20%20%23%20Dequeue%20elements%0A%20%20%20%20pop_front%20%3D%20deq.popleft%28%29%20%20%23%20Remove%20the%20front%20element%0A%20%20%20%20print%28%22Element%20removed%20from%20the%20front%3A%20pop_front%20%3D%22%2C%20pop_front%29%0A%20%20%20%20print%28%22After%20removing%20from%20the%20front%3A%20deque%20%3D%22%2C%20deq%29%0A%20%20%20%20pop_rear%20%3D%20deq.pop%28%29%20%20%23%20Remove%20the%20rear%20element%0A%20%20%20%20print%28%22Element%20removed%20from%20the%20rear%3A%20pop_rear%20%3D%22%2C%20pop_rear%29%0A%20%20%20%20print%28%22After%20removing%20from%20the%20rear%3A%20deque%20%3D%22%2C%20deq%29%0A%0A%20%20%20%20%23%20Get%20the%20deque%20size%0A%20%20%20%20size%20%3D%20len%28deq%29%0A%20%20%20%20print%28%22Deque%20size%3A%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20Check%20whether%20the%20deque%20is%20empty%0A%20%20%20%20is_empty%20%3D%20len%28deq%29%20%3D%3D%200%0A%20%20%20%20print%28%22Is%20the%20deque%20empty%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
## Deque Implementation *
## Implementing a deque *
The implementation of a deque is similar to that of a queue. You can choose either a linked list or an array as the underlying data structure.
A deque is implemented much like a queue, using either a linked list or an array as the underlying structure.
### Doubly Linked List Implementation
### Implementation with a doubly linked list
Reviewing the previous section, we used a regular singly linked list to implement a queue because it conveniently allows deleting the head node (corresponding to dequeue) and adding new nodes after the tail node (corresponding to enqueue).
In the previous section, we used a singly linked list for a queue because it easily supports removing the head for dequeueing and adding after the tail for enqueueing.
For a deque, both the front and rear can perform enqueue and dequeue operations. In other words, a deque needs to implement operations in the opposite direction as well. For this reason, we use a "doubly linked list" as the underlying data structure for the deque.
A deque supports both insertion and removal at both ends. It therefore needs the symmetric operations in the other direction as well. For this reason, we use a doubly linked list.
As shown in the figure below, we treat the head and tail nodes of the doubly linked list as the front and rear of the deque, implementing functionality to add and remove nodes at both ends.
As shown below, treat the list's head and tail as the deque's front and rear, and support adding and removing nodes at both ends.
=== "<1>"
![Enqueue and dequeue operations in linked list implementation of deque](deque.assets/linkedlist_deque_step1.png)
![Insertion and removal in a linked-list deque](deque.assets/linkedlist_deque_step1.png)
=== "<2>"
![linkedlist_deque_push_last](deque.assets/linkedlist_deque_step2_push_last.png)
@@ -414,18 +414,18 @@ As shown in the figure below, we treat the head and tail nodes of the doubly lin
=== "<5>"
![linkedlist_deque_pop_first](deque.assets/linkedlist_deque_step5_pop_first.png)
The implementation code is shown below:
The implementation is as follows:
```src
[file]{linkedlist_deque}-[class]{linked_list_deque}-[func]{}
```
### Array Implementation
### Implementation with an array
As shown in the figure below, similar to implementing a queue based on an array, we can also use a circular array to implement a deque.
As with an array-based queue, we can use a circular array to implement a deque, as shown below.
=== "<1>"
![Enqueue and dequeue operations in array implementation of deque](deque.assets/array_deque_step1.png)
![Insertion and removal in an array-based deque](deque.assets/array_deque_step1.png)
=== "<2>"
![array_deque_push_last](deque.assets/array_deque_step2_push_last.png)
@@ -439,14 +439,14 @@ As shown in the figure below, similar to implementing a queue based on an array,
=== "<5>"
![array_deque_pop_first](deque.assets/array_deque_step5_pop_first.png)
Based on the queue implementation, we only need to add methods for "enqueue at front" and "dequeue from rear":
Starting with the queue implementation, we need only add methods for insertion at the front and removal at the rear:
```src
[file]{array_deque}-[class]{array_deque}-[func]{}
```
## Deque Applications
## Applications
A deque combines the logic of both stacks and queues. **Therefore, it can implement all application scenarios of both, while providing greater flexibility**.
A deque combines stack and queue behavior, **so it supports all their applications while offering greater flexibility**.
We know that the "undo" function in software is typically implemented using a stack: the system pushes each change operation onto the stack and then implements undo through pop. However, considering system resource limitations, software usually limits the number of undo steps (for example, only allowing 50 steps to be saved). When the stack length exceeds 50, the software needs to perform a deletion operation at the bottom of the stack (front of the queue). **But a stack cannot implement this functionality, so a deque is needed to replace the stack**. Note that the core logic of "undo" still follows the LIFO principle of a stack; it's just that the deque can more flexibly implement some additional logic.
Software undo is usually implemented with a stack: the system uses `push` to record each change and `pop` to undo it. Because resources are limited, software often restricts the history to a fixed number of steps, such as $50$. When the stack grows beyond $50$, the oldest entry must be removed from the bottom, the front of the deque. **A stack cannot provide this operation, so a deque is needed instead**. The core undo behavior still follows last-in, first-out order; the deque simply provides flexibility for the additional logic.

View File

@@ -1,10 +1,10 @@
# Exercises
## Concept Review
## Check your understanding
### Which Element Leaves a Stack or Queue First?
### Which element comes out first in a stack or queue?
Prepare an empty stack `S` and an empty queue `Q`. Perform the same sequence of operations on each one:
Start with an empty stack `S` and an empty queue `Q`. Perform the same operations on each:
Step 1: Add `A`.
Step 2: Add `B`.
@@ -12,46 +12,46 @@ Step 3: Remove and record one element.
Step 4: Add `C`.
Step 5: Keep removing and recording elements until the container is empty.
Write the order in which elements are removed from `S` and from `Q`. Explain the difference using "last-in-first-out" or "first-in-first-out."
Write the order in which elements are removed from `S` and from `Q`. Explain the difference using last in, first out or first in, first out.
??? success "Answer"
??? success "Reference answer"
The removal order for stack `S` is `B, C, A`. After the elements `A, B` are added, the most recently added element, `B`, is popped first. After `C` is added,
`C, A` are popped in that order. This is "last-in-first-out."
The removal order for stack `S` is `B, C, A`. After adding `A, B`, we first pop `B`, the most recently added element, and then add `C`.
We then pop `C, A` in order. This is last in, first out.
The removal order for queue `Q` is `A, B, C`. After the elements `A, B` are added, the earliest added element, `A`, is removed first.
After `C` is added, `B, C` are removed in that order. This is "first-in-first-out."
The removal order for queue `Q` is `A, B, C`. After adding `A, B`, we first remove `A`, the earliest element added.
We then add `C` and remove `B, C` in order. This is first in, first out.
### What Happens When the Rear Passes the End of the Array?
### What happens when the rear passes the end of the array?
A queue is implemented with a circular array of length 5, whose indices are `0–4`.
Currently, `front = 3` and `size = 2`; `A, B` are stored at indices 3 and 4, respectively.
A queue uses a circular array of length 5, with indices `0-4`.
Currently, `front = 3` and `size = 2`, with queue elements `A, B` at indices 3 and 4, respectively.
<!-- numbered-subquestions -->
1. When `C` is enqueued, at which index should `C` be stored? What is `size` after the enqueue?
2. Next, dequeue once. Which element is removed? What are the new values of `front` and `size`?
3. What is the logical order from the front to the rear now? Does dequeuing require moving the other elements in the array? Why or why not?
1. When enqueueing `C`, at which index should `C` be placed? What is `size` afterward?
2. If we then dequeue once, which element is removed? What are the new values of `front` and `size`?
3. What is the logical order from front to rear now? Does dequeuing require moving the other array elements? Why?
??? success "Answer"
??? success "Reference answer"
1. The new element's position is
`(front + size) % 5 = (3 + 2) % 5 = 0`,
so `C` is stored at index 0. After the enqueue, `size = 3`.
so `C` goes at index 0. After enqueueing, `size = 3`.
2. Dequeuing removes the current front element, `A`. The new front index is
2. Dequeueing removes the current front element, `A`. The new front index is
`(3 + 1) % 5 = 4`, so `front = 4` and `size = 2`.
3. The logical order of valid elements is `B, C`, with `B` at index 4 and `C` at index 0.
Dequeuing requires only changing `front` and `size`. The circular array uses the remainder operation to wrap the index back to the beginning,
so there is no need to shift all the other elements forward.
3. The valid elements are logically ordered as `B, C`, with `B` at index 4 and `C` at index 0.
Dequeueing only advances `front` and updates `size`. The circular array uses the remainder operation to wrap indices back to the beginning,
so the other elements do not need to shift forward together.
### Operations at Both Ends of a Deque
### Operations at both ends of a deque
Here, `push_first` adds an element at the front, `push_last` adds one at the rear,
`pop_first` removes one from the front, and `pop_last` removes one from the rear.
Here, `push_first` adds at the front, `push_last` adds at the rear,
`pop_first` removes from the front, and `pop_last` removes from the rear.
Perform the following operations on an empty deque `deq`:
Starting with an empty deque `deq`, perform:
1. `push_last(A)`
2. `push_last(B)`
@@ -62,38 +62,38 @@ Perform the following operations on an empty deque `deq`:
<!-- numbered-subquestions -->
1. Which elements are returned by the two pop operations?
2. After all operations are complete, which elements remain from front to rear?
3. Examine the six operations. Can a queue that allows insertion only at the rear and removal only at the front perform all of them? If not, identify the operations it cannot perform. Then state whether a deque can perform them and explain why.
1. Which elements are removed by the two pop operations?
2. Which elements remain, from front to rear, after all the operations?
3. Examine these six steps. Can a queue that allows additions only at the rear and removals only at the front perform them all? If not, identify the unsupported operations. Then explain whether a deque can perform them all, and why.
??? success "Answer"
??? success "Reference answer"
After the first three steps, the deque from front to rear is `[C, A, B]`.
After the first three steps, the deque contains `[C, A, B]` from front to rear.
<!-- numbered-subquestions -->
1. `pop_last()` removes `B`. After `D` is added, the deque is `[C, A, D]`,
and `pop_first()` then removes `C`.
1. `pop_last()` removes `B`. After adding `D`, the deque is `[C, A, D]`.
Then `pop_first()` removes `C`.
2. `[A, D]` remains.
2. The remaining elements are `[A, D]`.
3. A queue that permits insertion only at the rear and removal only at the front cannot perform all the operations.
Step 3, `push_first(C)`, requires insertion at the front, and Step 4, `pop_last()`, requires removal at the rear. Both are outside the operations supported by such a queue.
A deque permits insertion and removal at both ends, so it can perform all six operations.
3. A queue that allows additions only at the rear and removals only at the front cannot perform every operation:
step 3, `push_first(C)`, adds at the front, and step 4, `pop_last()`, removes from the rear. Neither operation is supported by that queue.
A deque supports additions and removals at both ends, so it can perform all six steps.
## Programming Exercises
## Programming exercises
### Check a Bracket Sequence
### Checking a bracket sequence
Given a string `s` containing only the three types of brackets `()`, `[]`, and `{}`, use a stack to determine whether the string is valid.
Given a string `s` containing only the three types of brackets `()`, `[]`, and `{}`, use a stack to determine whether it is valid.
A valid sequence must satisfy both conditions: every closing bracket matches the type of the most recent unmatched opening bracket,
and no unmatched opening bracket remains after the traversal. Return a Boolean value for the result.
A valid sequence must satisfy both conditions: each closing bracket matches the type of the most recent unmatched opening bracket,
and no unmatched opening brackets remain at the end. Return a Boolean result.
??? tip "Hints"
1. You can create a mapping from each closing bracket to its matching opening bracket
2. When you encounter a closing bracket, first check whether the stack is empty, and then check whether the top matches
3. The stack must also be empty after the traversal
1. You can map each closing bracket to its matching opening bracket.
2. When you encounter a closing bracket, first check whether the stack is empty, then check whether its top matches.
3. The stack must also be empty when the scan finishes.
[LeetCode](https://leetcode.com/problems/valid-parentheses/){ .rounded-button .exercise-button target="_blank" rel="noopener noreferrer" }

View File

@@ -1,9 +1,9 @@
# Stacks and Queues
# Stacks and queues
![Stacks and Queues](../assets/covers/chapter_stack_and_queue.jpg)
![Stacks and queues](../assets/covers/chapter_stack_and_queue.jpg)
!!! abstract
A stack is like cats piled on top of one another, while a queue is like cats lining up.
They represent the logical relationships of LIFO (Last In, First Out) and FIFO (First In, First Out), respectively.
A stack is like cats piled on top of one another; a queue is like cats standing in line.
They represent last-in, first-out and first-in, first-out order, respectively.

View File

@@ -1,33 +1,33 @@
# Queue
# Queues
A <u>queue</u> is a linear data structure that follows the First In, First Out (FIFO) rule. As the name suggests, it models people lining up: newcomers continuously join the rear of the queue, while the people at the front leave one by one.
A <u>queue</u> is a linear data structure that follows a first-in, first-out rule. It models a line of people: newcomers join at the back, while those at the front leave one by one.
As shown in the figure below, we call the front of the queue the "front" and the end the "rear." The operation of adding an element to the rear is called "enqueue," and the operation of removing the front element is called "dequeue."
As shown below, the two ends are called the “front” and the “rear.” Adding an element at the rear is called “enqueueing,” and removing an element from the front is called “dequeueing.”
![FIFO rule of queue](queue.assets/queue_operations.png)
![The first-in, first-out rule of a queue](queue.assets/queue_operations.png)
## Common Queue Operations
## Common queue operations
The common operations on a queue are shown in the table below. Note that method names may vary across programming languages. Here, we use the same naming convention as for stacks.
The table below lists common operations. Method names vary between programming languages; here we use the same names as for stacks.
<p align="center"> Table <id> &nbsp; Efficiency of Queue Operations </p>
<p align="center"> Table <id> &nbsp; Efficiency of queue operations </p>
| Method | Description | Time Complexity |
| -------- | ------------------------------------------ | --------------- |
| `push()` | Enqueue element, add element to rear | $O(1)$ |
| `pop()` | Dequeue front element | $O(1)$ |
| `peek()` | Access front element | $O(1)$ |
| Method | Description | Time complexity |
| -------- | ---------------------------- | ---------- |
| `push()` | Enqueue an element at the rear | $O(1)$ |
| `pop()` | Dequeue the front element | $O(1)$ |
| `peek()` | Access the front element | $O(1)$ |
We can directly use the queue classes provided by the programming language:
We can use a queue class already provided by the programming language:
=== "Python"
```python title="queue.py"
from collections import deque
# Initialize queue
# In Python, we generally use the deque class as a queue
# Although queue.Queue() is a pure queue class, it is not very user-friendly, so it is not recommended
# Initialize a queue
# In Python, we usually use the deque class as a queue
# Although queue.Queue() is a dedicated queue class, it is less convenient and is not recommended here
que: deque[int] = deque()
# Enqueue elements
@@ -37,23 +37,23 @@ We can directly use the queue classes provided by the programming language:
que.append(5)
que.append(4)
# Access front element
# Access the front element
front: int = que[0]
# Dequeue element
# Dequeue an element
pop: int = que.popleft()
# Get queue length
# Get the queue size
size: int = len(que)
# Check if queue is empty
# Check whether the queue is empty
is_empty: bool = len(que) == 0
```
=== "C++"
```cpp title="queue.cpp"
/* Initialize queue */
/* Initialize a queue */
queue<int> queue;
/* Enqueue elements */
@@ -63,23 +63,23 @@ We can directly use the queue classes provided by the programming language:
queue.push(5);
queue.push(4);
/* Access front element */
/* Access the front element */
int front = queue.front();
/* Dequeue element */
/* Dequeue an element */
queue.pop();
/* Get queue length */
/* Get the queue size */
int size = queue.size();
/* Check if queue is empty */
/* Check whether the queue is empty */
bool empty = queue.empty();
```
=== "Java"
```java title="queue.java"
/* Initialize queue */
/* Initialize a queue */
Queue<Integer> queue = new LinkedList<>();
/* Enqueue elements */
@@ -89,23 +89,23 @@ We can directly use the queue classes provided by the programming language:
queue.offer(5);
queue.offer(4);
/* Access front element */
/* Access the front element */
int peek = queue.peek();
/* Dequeue element */
/* Dequeue an element */
int pop = queue.poll();
/* Get queue length */
/* Get the queue size */
int size = queue.size();
/* Check if queue is empty */
/* Check whether the queue is empty */
boolean isEmpty = queue.isEmpty();
```
=== "C#"
```csharp title="queue.cs"
/* Initialize queue */
/* Initialize a queue */
Queue<int> queue = new();
/* Enqueue elements */
@@ -115,24 +115,24 @@ We can directly use the queue classes provided by the programming language:
queue.Enqueue(5);
queue.Enqueue(4);
/* Access front element */
/* Access the front element */
int peek = queue.Peek();
/* Dequeue element */
/* Dequeue an element */
int pop = queue.Dequeue();
/* Get queue length */
/* Get the queue size */
int size = queue.Count;
/* Check if queue is empty */
/* Check whether the queue is empty */
bool isEmpty = queue.Count == 0;
```
=== "Go"
```go title="queue_test.go"
/* Initialize queue */
// In Go, use list as a queue
/* Initialize a queue */
// In Go, use a list as a queue
queue := list.New()
/* Enqueue elements */
@@ -142,25 +142,25 @@ We can directly use the queue classes provided by the programming language:
queue.PushBack(5)
queue.PushBack(4)
/* Access front element */
/* Access the front element */
peek := queue.Front()
/* Dequeue element */
/* Dequeue an element */
pop := queue.Front()
queue.Remove(pop)
/* Get queue length */
/* Get the queue size */
size := queue.Len()
/* Check if queue is empty */
/* Check whether the queue is empty */
isEmpty := queue.Len() == 0
```
=== "Swift"
```swift title="queue.swift"
/* Initialize queue */
// Swift does not have a built-in queue class, can use Array as a queue
/* Initialize a queue */
// Swift has no built-in queue class; use an Array as a queue
var queue: [Int] = []
/* Enqueue elements */
@@ -170,25 +170,25 @@ We can directly use the queue classes provided by the programming language:
queue.append(5)
queue.append(4)
/* Access front element */
/* Access the front element */
let peek = queue.first!
/* Dequeue element */
// Since it's an array, removeFirst has O(n) complexity
/* Dequeue an element */
// Because this is an array, removeFirst takes O(n) time
let pop = queue.removeFirst()
/* Get queue length */
/* Get the queue size */
let size = queue.count
/* Check if queue is empty */
/* Check whether the queue is empty */
let isEmpty = queue.isEmpty
```
=== "JS"
```javascript title="queue.js"
/* Initialize queue */
// JavaScript does not have a built-in queue, can use Array as a queue
/* Initialize a queue */
// JavaScript has no built-in queue; use an Array as a queue
const queue = [];
/* Enqueue elements */
@@ -198,25 +198,25 @@ We can directly use the queue classes provided by the programming language:
queue.push(5);
queue.push(4);
/* Access front element */
/* Access the front element */
const peek = queue[0];
/* Dequeue element */
// The underlying structure is an array, so shift() has O(n) time complexity
/* Dequeue an element */
// The underlying structure is an array, so shift() takes O(n) time
const pop = queue.shift();
/* Get queue length */
/* Get the queue size */
const size = queue.length;
/* Check if queue is empty */
/* Check whether the queue is empty */
const empty = queue.length === 0;
```
=== "TS"
```typescript title="queue.ts"
/* Initialize queue */
// TypeScript does not have a built-in queue, can use Array as a queue
/* Initialize a queue */
// TypeScript has no built-in queue; use an Array as a queue
const queue: number[] = [];
/* Enqueue elements */
@@ -226,25 +226,25 @@ We can directly use the queue classes provided by the programming language:
queue.push(5);
queue.push(4);
/* Access front element */
/* Access the front element */
const peek = queue[0];
/* Dequeue element */
// The underlying structure is an array, so shift() has O(n) time complexity
/* Dequeue an element */
// The underlying structure is an array, so shift() takes O(n) time
const pop = queue.shift();
/* Get queue length */
/* Get the queue size */
const size = queue.length;
/* Check if queue is empty */
/* Check whether the queue is empty */
const empty = queue.length === 0;
```
=== "Dart"
```dart title="queue.dart"
/* Initialize queue */
// In Dart, the Queue class is a deque and can also be used as a queue
/* Initialize a queue */
// In Dart, Queue is a deque and can also be used as a queue
Queue<int> queue = Queue();
/* Enqueue elements */
@@ -254,24 +254,24 @@ We can directly use the queue classes provided by the programming language:
queue.add(5);
queue.add(4);
/* Access front element */
/* Access the front element */
int peek = queue.first;
/* Dequeue element */
/* Dequeue an element */
int pop = queue.removeFirst();
/* Get queue length */
/* Get the queue size */
int size = queue.length;
/* Check if queue is empty */
/* Check whether the queue is empty */
bool isEmpty = queue.isEmpty;
```
=== "Rust"
```rust title="queue.rs"
/* Initialize deque */
// In Rust, use deque as a regular queue
/* Initialize a deque */
// In Rust, use a deque as an ordinary queue
let mut deque: VecDeque<u32> = VecDeque::new();
/* Enqueue elements */
@@ -281,31 +281,31 @@ We can directly use the queue classes provided by the programming language:
deque.push_back(5);
deque.push_back(4);
/* Access front element */
/* Access the front element */
if let Some(front) = deque.front() {
}
/* Dequeue element */
/* Dequeue an element */
if let Some(pop) = deque.pop_front() {
}
/* Get queue length */
/* Get the queue size */
let size = deque.len();
/* Check if queue is empty */
/* Check whether the queue is empty */
let is_empty = deque.is_empty();
```
=== "C"
```c title="queue.c"
// C does not provide a built-in queue
// C provides no built-in queue
```
=== "Kotlin"
```kotlin title="queue.kt"
/* Initialize queue */
/* Initialize a queue */
val queue = LinkedList<Int>()
/* Enqueue elements */
@@ -315,24 +315,24 @@ We can directly use the queue classes provided by the programming language:
queue.offer(5)
queue.offer(4)
/* Access front element */
/* Access the front element */
val peek = queue.peek()
/* Dequeue element */
/* Dequeue an element */
val pop = queue.poll()
/* Get queue length */
/* Get the queue size */
val size = queue.size
/* Check if queue is empty */
/* Check whether the queue is empty */
val isEmpty = queue.isEmpty()
```
=== "Ruby"
```ruby title="queue.rb"
# Initialize queue
# Ruby's built-in queue (Thread::Queue) does not have peek and traversal methods, can use Array as a queue
# Initialize a queue
# Ruby's built-in Thread::Queue has no peek or traversal methods; use an Array as a queue
queue = []
# Enqueue elements
@@ -342,34 +342,34 @@ We can directly use the queue classes provided by the programming language:
queue.push(5)
queue.push(4)
# Access front element
# Access the front element of the queue
peek = queue.first
# Dequeue element
# Please note that since it's an array, Array#shift has O(n) time complexity
# Dequeue an element
# Note that this is an array, so Array#shift takes O(n) time
pop = queue.shift
# Get queue length
# Get the queue size
size = queue.length
# Check if queue is empty
# Check whether the queue is empty
is_empty = queue.empty?
```
??? pythontutor "Code Visualization"
??? pythontutor "Visualize execution"
https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%98%9F%E5%88%97%0A%20%20%20%20%23%20%E5%9C%A8%20Python%20%E4%B8%AD%EF%BC%8C%E6%88%91%E4%BB%AC%E4%B8%80%E8%88%AC%E5%B0%86%E5%8F%8C%E5%90%91%E9%98%9F%E5%88%97%E7%B1%BB%20deque%20%E7%9C%8B%E4%BD%9C%E9%98%9F%E5%88%97%E4%BD%BF%E7%94%A8%0A%20%20%20%20%23%20%E8%99%BD%E7%84%B6%20queue.Queue%28%29%20%E6%98%AF%E7%BA%AF%E6%AD%A3%E7%9A%84%E9%98%9F%E5%88%97%E7%B1%BB%EF%BC%8C%E4%BD%86%E4%B8%8D%E5%A4%AA%E5%A5%BD%E7%94%A8%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E9%98%9F%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22%E9%98%9F%E5%88%97%20que%20%3D%22,%20que%29%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22%E9%98%9F%E9%A6%96%E5%85%83%E7%B4%A0%20front%20%3D%22,%20front%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E9%98%9F%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22%E5%87%BA%E9%98%9F%E5%85%83%E7%B4%A0%20pop%20%3D%22,%20pop%29%0A%20%20%20%20print%28%22%E5%87%BA%E9%98%9F%E5%90%8E%20que%20%3D%22,%20que%29%0A%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E9%98%9F%E5%88%97%E7%9A%84%E9%95%BF%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22%E9%98%9F%E5%88%97%E9%95%BF%E5%BA%A6%20size%20%3D%22,%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%20%3D%22,%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=from%20collections%20import%20deque%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20queue%0A%20%20%20%20%23%20In%20Python%2C%20we%20usually%20use%20the%20deque%20class%20as%20a%20queue%0A%20%20%20%20%23%20Although%20queue.Queue%28%29%20is%20a%20dedicated%20queue%20class%2C%20it%20is%20less%20convenient%0A%20%20%20%20que%20%3D%20deque%28%29%0A%0A%20%20%20%20%23%20Enqueue%20elements%0A%20%20%20%20que.append%281%29%0A%20%20%20%20que.append%283%29%0A%20%20%20%20que.append%282%29%0A%20%20%20%20que.append%285%29%0A%20%20%20%20que.append%284%29%0A%20%20%20%20print%28%22Queue%3A%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20Access%20the%20front%20element%0A%20%20%20%20front%20%3D%20que%5B0%5D%0A%20%20%20%20print%28%22Front%20element%3A%20front%20%3D%22%2C%20front%29%0A%0A%20%20%20%20%23%20Dequeue%20an%20element%0A%20%20%20%20pop%20%3D%20que.popleft%28%29%0A%20%20%20%20print%28%22Dequeued%20element%3A%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22After%20dequeuing%3A%20que%20%3D%22%2C%20que%29%0A%0A%20%20%20%20%23%20Get%20the%20queue%20size%0A%20%20%20%20size%20%3D%20len%28que%29%0A%20%20%20%20print%28%22Queue%20size%3A%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20Check%20whether%20the%20queue%20is%20empty%0A%20%20%20%20is_empty%20%3D%20len%28que%29%20%3D%3D%200%0A%20%20%20%20print%28%22Is%20the%20queue%20empty%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
## Queue Implementation
## Implementing a queue
To implement a queue, we need a data structure that allows adding elements at one end and removing elements at the other end. Both linked lists and arrays meet this requirement.
A queue needs a data structure that allows insertion at one end and deletion at the other. Both linked lists and arrays can meet this requirement.
### Linked List Implementation
### Implementation with a linked list
As shown in the figure below, we can treat the "head node" and "tail node" of a linked list as the "front" and "rear" of the queue, respectively, with the rule that nodes can only be added at the rear and removed from the front.
As shown below, treat the linked list's head and tail as the queue's front and rear. Nodes may be added only at the rear and removed only from the front.
=== "<1>"
![Enqueue and dequeue operations in linked list implementation of queue](queue.assets/linkedlist_queue_step1.png)
![Enqueue and dequeue in a linked-list queue](queue.assets/linkedlist_queue_step1.png)
=== "<2>"
![linkedlist_queue_push](queue.assets/linkedlist_queue_step2_push.png)
@@ -377,27 +377,27 @@ As shown in the figure below, we can treat the "head node" and "tail node" of a
=== "<3>"
![linkedlist_queue_pop](queue.assets/linkedlist_queue_step3_pop.png)
Below is the code for implementing a queue using a linked list:
Here is an implementation using a linked list:
```src
[file]{linkedlist_queue}-[class]{linked_list_queue}-[func]{}
```
### Array Implementation
### Implementation with an array
Deleting the first element in an array has a time complexity of $O(n)$, which would make the dequeue operation inefficient. However, we can use the following clever method to avoid this problem.
Removing the first element of an array takes $O(n)$ time, which would make dequeueing inefficient. A useful technique avoids this problem.
We can use a variable `front` to point to the index of the front element and maintain a variable `size` to record the queue length. We define `rear = front + size`, which calculates the position right after the rear element.
Use a variable `front` for the index of the front element and a variable `size` for the queue's length. Define `rear = front + size`, so `rear` points to the position immediately after the last element.
Based on this design, **the valid interval containing elements in the array is `[front, rear - 1]`**. The implementation methods for various operations are shown in the figure below:
With this design, **the occupied interval is `[front, rear - 1]`**. Operations work as shown below.
- Enqueue operation: Assign the input element to the `rear` index and increase `size` by 1.
- Dequeue operation: Simply increase `front` by 1 and decrease `size` by 1.
- Enqueue: assign the new element to index `rear` and increase `size` by 1.
- Dequeue: increase `front` by 1 and decrease `size` by 1.
As you can see, both enqueue and dequeue operations require only one operation, with a time complexity of $O(1)$.
Both operations require only a constant amount of work and take $O(1)$ time.
=== "<1>"
![Enqueue and dequeue operations in array implementation of queue](queue.assets/array_queue_step1.png)
![Enqueue and dequeue in an array-based queue](queue.assets/array_queue_step1.png)
=== "<2>"
![array_queue_push](queue.assets/array_queue_step2_push.png)
@@ -405,19 +405,19 @@ As you can see, both enqueue and dequeue operations require only one operation,
=== "<3>"
![array_queue_pop](queue.assets/array_queue_step3_pop.png)
You may notice a problem: as we continuously enqueue and dequeue, both `front` and `rear` move to the right. **When they reach the end of the array, they cannot continue moving**. To solve this problem, we can treat the array as a "circular array" with head and tail connected.
There is a problem: repeated enqueueing and dequeueing move both `front` and `rear` to the right, **and they cannot continue once they reach the end of the array**. To solve this, treat the array as circular, with its end connected to its beginning.
For a circular array, we need to let `front` or `rear` wrap around to the beginning of the array when they cross the end. This periodic pattern can be implemented using the "modulo operation," as shown in the code below:
When `front` or `rear` passes the array's end, wrap it back to the beginning. The remainder operation implements this cyclic behavior:
```src
[file]{array_queue}-[class]{array_queue}-[func]{}
```
The queue implemented above still has limitations: its length is immutable. However, this problem is not difficult to solve. We can replace the array with a dynamic array to introduce an expansion mechanism. Interested readers can try to implement this themselves.
This queue still has a limitation: its capacity is fixed. We can address it by replacing the array with a dynamic array and adding resizing. Interested readers can try implementing this themselves.
The comparison conclusions for the two implementations are consistent with those for stacks and will not be repeated here.
The comparison between these two implementations is the same as for stacks, so we will not repeat it here.
## Typical Applications of Queue
## Typical applications
- **Taobao orders**. After shoppers place orders, the orders are added to a queue, and the system subsequently processes the orders in the queue according to their sequence. During Double Eleven, massive orders are generated in a short time, and high concurrency becomes a key challenge that engineers need to tackle.
- **Various to-do tasks**. Any scenario that needs to implement "first come, first served" functionality, such as a printer's task queue or a restaurant's order queue, can effectively maintain the processing order using queues.
- **Taobao orders**. When a shopper places an order, it enters a queue, and the system processes orders in sequence. During the Singles' Day shopping festival, enormous numbers of orders arrive in a short time, making high concurrency a major engineering challenge.
- **Tasks awaiting processing**. Queues preserve processing order wherever first-come, first-served behavior is needed, such as printer jobs or restaurant orders.

View File

@@ -1,32 +1,32 @@
# Stack
# Stacks
A <u>stack</u> is a linear data structure that follows the Last In, First Out (LIFO) principle.
A <u>stack</u> is a linear data structure that follows a last-in, first-out rule.
We can compare a stack to a pile of plates on a table. If we specify that only one plate can be moved at a time, then to get the bottom plate, we must first remove the plates above it one by one. If we replace the plates with various types of elements (such as integers, characters, objects, etc.), we get the stack data structure.
Think of a stack of plates on a table. If we can move only one plate at a time, reaching the bottom plate requires removing all the plates above it first. Replace the plates with elements such as integers, characters, or objects, and we have a stack.
As shown in the figure below, we call the top of the stacked elements the "top" and the bottom the "bottom." The operation of adding an element to the top is called "push," and the operation of removing the top element is called "pop."
As shown below, the upper end is the “top” of the stack and the lower end is the “bottom.” Adding an element to the top is called “pushing,” and removing the top element is called “popping.”
![LIFO rule of stack](stack.assets/stack_operations.png)
![The last-in, first-out rule of a stack](stack.assets/stack_operations.png)
## Common Stack Operations
## Common stack operations
The common operations on a stack are shown in the table below. The specific method names depend on the programming language used. Here, we use the common naming convention of `push()`, `pop()`, and `peek()`.
The table below lists common operations. Actual method names depend on the programming language; here we use the familiar names `push()`, `pop()`, and `peek()`.
<p align="center"> Table <id> &nbsp; Efficiency of Stack Operations </p>
<p align="center"> Table <id> &nbsp; Efficiency of stack operations </p>
| Method | Description | Time Complexity |
| -------- | ---------------------------------------------- | --------------- |
| `push()` | Push element onto stack (add to top) | $O(1)$ |
| `pop()` | Pop top element from stack | $O(1)$ |
| `peek()` | Access top element | $O(1)$ |
| Method | Description | Time complexity |
| -------- | ---------------------- | ---------- |
| `push()` | Push an element onto the top | $O(1)$ |
| `pop()` | Remove the top element | $O(1)$ |
| `peek()` | Access the top element | $O(1)$ |
Typically, we can directly use the built-in stack class provided by the programming language. However, some languages may not provide a dedicated stack class. In such cases, we can use the language's "array" or "linked list" as a stack and simply avoid using operations unrelated to stack behavior.
We can usually use a language's built-in stack class. If no dedicated class is provided, use an array or linked list as a stack and avoid operations unrelated to stack behavior.
=== "Python"
```python title="stack.py"
# Initialize stack
# Python does not have a built-in stack class, can use list as a stack
# Initialize a stack
# Python has no built-in stack class; use a list as a stack
stack: list[int] = []
# Push elements
@@ -36,23 +36,23 @@ Typically, we can directly use the built-in stack class provided by the programm
stack.append(5)
stack.append(4)
# Access top element
# Access the top element
peek: int = stack[-1]
# Pop element
# Pop an element
pop: int = stack.pop()
# Get stack length
# Get the stack size
size: int = len(stack)
# Check if empty
# Check whether the stack is empty
is_empty: bool = len(stack) == 0
```
=== "C++"
```cpp title="stack.cpp"
/* Initialize stack */
/* Initialize a stack */
stack<int> stack;
/* Push elements */
@@ -62,23 +62,23 @@ Typically, we can directly use the built-in stack class provided by the programm
stack.push(5);
stack.push(4);
/* Access top element */
/* Access the top element */
int top = stack.top();
/* Pop element */
/* Pop an element */
stack.pop(); // No return value
/* Get stack length */
/* Get the stack size */
int size = stack.size();
/* Check if empty */
/* Check whether the stack is empty */
bool empty = stack.empty();
```
=== "Java"
```java title="stack.java"
/* Initialize stack */
/* Initialize a stack */
Stack<Integer> stack = new Stack<>();
/* Push elements */
@@ -88,23 +88,23 @@ Typically, we can directly use the built-in stack class provided by the programm
stack.push(5);
stack.push(4);
/* Access top element */
/* Access the top element */
int peek = stack.peek();
/* Pop element */
/* Pop an element */
int pop = stack.pop();
/* Get stack length */
/* Get the stack size */
int size = stack.size();
/* Check if empty */
/* Check whether the stack is empty */
boolean isEmpty = stack.isEmpty();
```
=== "C#"
```csharp title="stack.cs"
/* Initialize stack */
/* Initialize a stack */
Stack<int> stack = new();
/* Push elements */
@@ -114,24 +114,24 @@ Typically, we can directly use the built-in stack class provided by the programm
stack.Push(5);
stack.Push(4);
/* Access top element */
/* Access the top element */
int peek = stack.Peek();
/* Pop element */
/* Pop an element */
int pop = stack.Pop();
/* Get stack length */
/* Get the stack size */
int size = stack.Count;
/* Check if empty */
/* Check whether the stack is empty */
bool isEmpty = stack.Count == 0;
```
=== "Go"
```go title="stack_test.go"
/* Initialize stack */
// In Go, it is recommended to use Slice as a stack
/* Initialize a stack */
// In Go, a slice is recommended for use as a stack
var stack []int
/* Push elements */
@@ -141,25 +141,25 @@ Typically, we can directly use the built-in stack class provided by the programm
stack = append(stack, 5)
stack = append(stack, 4)
/* Access top element */
/* Access the top element */
peek := stack[len(stack)-1]
/* Pop element */
/* Pop an element */
pop := stack[len(stack)-1]
stack = stack[:len(stack)-1]
/* Get stack length */
/* Get the stack size */
size := len(stack)
/* Check if empty */
/* Check whether the stack is empty */
isEmpty := len(stack) == 0
```
=== "Swift"
```swift title="stack.swift"
/* Initialize stack */
// Swift does not have a built-in stack class, can use Array as a stack
/* Initialize a stack */
// Swift has no built-in stack class; use an Array as a stack
var stack: [Int] = []
/* Push elements */
@@ -169,24 +169,24 @@ Typically, we can directly use the built-in stack class provided by the programm
stack.append(5)
stack.append(4)
/* Access top element */
/* Access the top element */
let peek = stack.last!
/* Pop element */
/* Pop an element */
let pop = stack.removeLast()
/* Get stack length */
/* Get the stack size */
let size = stack.count
/* Check if empty */
/* Check whether the stack is empty */
let isEmpty = stack.isEmpty
```
=== "JS"
```javascript title="stack.js"
/* Initialize stack */
// JavaScript does not have a built-in stack class, can use Array as a stack
/* Initialize a stack */
// JavaScript has no built-in stack class; use an Array as a stack
const stack = [];
/* Push elements */
@@ -196,24 +196,24 @@ Typically, we can directly use the built-in stack class provided by the programm
stack.push(5);
stack.push(4);
/* Access top element */
/* Access the top element */
const peek = stack[stack.length-1];
/* Pop element */
/* Pop an element */
const pop = stack.pop();
/* Get stack length */
/* Get the stack size */
const size = stack.length;
/* Check if empty */
/* Check whether the stack is empty */
const is_empty = stack.length === 0;
```
=== "TS"
```typescript title="stack.ts"
/* Initialize stack */
// TypeScript does not have a built-in stack class, can use Array as a stack
/* Initialize a stack */
// TypeScript has no built-in stack class; use an Array as a stack
const stack: number[] = [];
/* Push elements */
@@ -223,24 +223,24 @@ Typically, we can directly use the built-in stack class provided by the programm
stack.push(5);
stack.push(4);
/* Access top element */
/* Access the top element */
const peek = stack[stack.length - 1];
/* Pop element */
/* Pop an element */
const pop = stack.pop();
/* Get stack length */
/* Get the stack size */
const size = stack.length;
/* Check if empty */
/* Check whether the stack is empty */
const is_empty = stack.length === 0;
```
=== "Dart"
```dart title="stack.dart"
/* Initialize stack */
// Dart does not have a built-in stack class, can use List as a stack
/* Initialize a stack */
// Dart has no built-in stack class; use a List as a stack
List<int> stack = [];
/* Push elements */
@@ -250,24 +250,24 @@ Typically, we can directly use the built-in stack class provided by the programm
stack.add(5);
stack.add(4);
/* Access top element */
/* Access the top element */
int peek = stack.last;
/* Pop element */
/* Pop an element */
int pop = stack.removeLast();
/* Get stack length */
/* Get the stack size */
int size = stack.length;
/* Check if empty */
/* Check whether the stack is empty */
bool isEmpty = stack.isEmpty;
```
=== "Rust"
```rust title="stack.rs"
/* Initialize stack */
// Use Vec as a stack
/* Initialize a stack */
// Use a Vec as a stack
let mut stack: Vec<i32> = Vec::new();
/* Push elements */
@@ -277,29 +277,29 @@ Typically, we can directly use the built-in stack class provided by the programm
stack.push(5);
stack.push(4);
/* Access top element */
/* Access the top element */
let top = stack.last().unwrap();
/* Pop element */
/* Pop an element */
let pop = stack.pop().unwrap();
/* Get stack length */
/* Get the stack size */
let size = stack.len();
/* Check if empty */
/* Check whether the stack is empty */
let is_empty = stack.is_empty();
```
=== "C"
```c title="stack.c"
// C does not provide a built-in stack
// C provides no built-in stack
```
=== "Kotlin"
```kotlin title="stack.kt"
/* Initialize stack */
/* Initialize a stack */
val stack = Stack<Int>()
/* Push elements */
@@ -309,24 +309,24 @@ Typically, we can directly use the built-in stack class provided by the programm
stack.push(5)
stack.push(4)
/* Access top element */
/* Access the top element */
val peek = stack.peek()
/* Pop element */
/* Pop an element */
val pop = stack.pop()
/* Get stack length */
/* Get the stack size */
val size = stack.size
/* Check if empty */
/* Check whether the stack is empty */
val isEmpty = stack.isEmpty()
```
=== "Ruby"
```ruby title="stack.rb"
# Initialize stack
# Ruby does not have a built-in stack class, can use Array as a stack
# Initialize a stack
# Ruby has no built-in stack class; use an Array as a stack
stack = []
# Push elements
@@ -336,37 +336,37 @@ Typically, we can directly use the built-in stack class provided by the programm
stack << 5
stack << 4
# Access top element
# Access the top element
peek = stack.last
# Pop element
# Pop an element
pop = stack.pop
# Get stack length
# Get the stack size
size = stack.length
# Check if empty
# Check whether the stack is empty
is_empty = stack.empty?
```
??? pythontutor "Code Visualization"
??? pythontutor "Visualize execution"
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E6%A0%88%0A%20%20%20%20%23%20Python%20%E6%B2%A1%E6%9C%89%E5%86%85%E7%BD%AE%E7%9A%84%E6%A0%88%E7%B1%BB%EF%BC%8C%E5%8F%AF%E4%BB%A5%E6%8A%8A%20list%20%E5%BD%93%E4%BD%9C%E6%A0%88%E6%9D%A5%E4%BD%BF%E7%94%A8%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E6%A0%88%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22%E6%A0%88%20stack%20%3D%22,%20stack%29%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E6%A0%88%E9%A1%B6%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22%E6%A0%88%E9%A1%B6%E5%85%83%E7%B4%A0%20peek%20%3D%22,%20peek%29%0A%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%87%BA%E6%A0%88%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22%E5%87%BA%E6%A0%88%E5%85%83%E7%B4%A0%20pop%20%3D%22,%20pop%29%0A%20%20%20%20print%28%22%E5%87%BA%E6%A0%88%E5%90%8E%20stack%20%3D%22,%20stack%29%0A%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E6%A0%88%E7%9A%84%E9%95%BF%E5%BA%A6%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22%E6%A0%88%E7%9A%84%E9%95%BF%E5%BA%A6%20size%20%3D%22,%20size%29%0A%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22%E6%A0%88%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%20%3D%22,%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20stack%0A%20%20%20%20%23%20Python%20has%20no%20built-in%20stack%20class%3B%20use%20a%20list%20as%20a%20stack%0A%20%20%20%20stack%20%3D%20%5B%5D%0A%0A%20%20%20%20%23%20Push%20elements%0A%20%20%20%20stack.append%281%29%0A%20%20%20%20stack.append%283%29%0A%20%20%20%20stack.append%282%29%0A%20%20%20%20stack.append%285%29%0A%20%20%20%20stack.append%284%29%0A%20%20%20%20print%28%22Stack%3A%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20Access%20the%20top%20element%0A%20%20%20%20peek%20%3D%20stack%5B-1%5D%0A%20%20%20%20print%28%22Top%20element%3A%20peek%20%3D%22%2C%20peek%29%0A%0A%20%20%20%20%23%20Pop%20an%20element%0A%20%20%20%20pop%20%3D%20stack.pop%28%29%0A%20%20%20%20print%28%22Popped%20element%3A%20pop%20%3D%22%2C%20pop%29%0A%20%20%20%20print%28%22After%20popping%3A%20stack%20%3D%22%2C%20stack%29%0A%0A%20%20%20%20%23%20Get%20the%20stack%20size%0A%20%20%20%20size%20%3D%20len%28stack%29%0A%20%20%20%20print%28%22Stack%20size%3A%20size%20%3D%22%2C%20size%29%0A%0A%20%20%20%20%23%20Check%20whether%20the%20stack%20is%20empty%0A%20%20%20%20is_empty%20%3D%20len%28stack%29%20%3D%3D%200%0A%20%20%20%20print%28%22Is%20the%20stack%20empty%20%3D%22%2C%20is_empty%29&cumulative=false&curInstr=2&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
## Stack Implementation
## Implementing a stack
To gain a deeper understanding of how a stack operates, let's try implementing a stack class ourselves.
To understand how a stack works more deeply, let us implement a stack class ourselves.
A stack follows the LIFO principle, so we can only add or remove elements at the top. However, both arrays and linked lists allow adding and removing elements at any position. **Therefore, a stack can be viewed as a restricted array or linked list**. In other words, we can "shield" some irrelevant operations of arrays or linked lists so that their external logic conforms to the characteristics of a stack.
A stack follows last-in, first-out order, so elements can be added or removed only at the top. Arrays and linked lists allow insertion and deletion at arbitrary positions, **so a stack can be viewed as a restricted array or linked list**. By hiding irrelevant operations, we make its public behavior conform to the stack's rules.
### Linked List Implementation
### Implementation with a linked list
When implementing a stack using a linked list, we can treat the head node of the linked list as the top of the stack and the tail node as the base.
When implementing a stack with a linked list, treat the head as the top and the tail as the bottom.
As shown in the figure below, for the push operation, we simply insert an element at the head of the linked list. This node insertion method is called the "head insertion method." For the pop operation, we just need to remove the head node from the linked list.
As shown below, pushing simply inserts a node at the head, an operation called “head insertion.” Popping removes the head node.
=== "<1>"
![Push and pop operations in linked list implementation of stack](stack.assets/linkedlist_stack_step1.png)
![Push and pop in a linked-list stack](stack.assets/linkedlist_stack_step1.png)
=== "<2>"
![linkedlist_stack_push](stack.assets/linkedlist_stack_step2_push.png)
@@ -374,18 +374,18 @@ As shown in the figure below, for the push operation, we simply insert an elemen
=== "<3>"
![linkedlist_stack_pop](stack.assets/linkedlist_stack_step3_pop.png)
Below is sample code for implementing a stack based on a linked list:
Here is an implementation using a linked list:
```src
[file]{linkedlist_stack}-[class]{linked_list_stack}-[func]{}
```
### Array Implementation
### Implementation with an array
When implementing a stack using an array, we can treat the end of the array as the top of the stack. As shown in the figure below, push and pop operations correspond to adding and removing elements at the end of the array, both with a time complexity of $O(1)$.
For an array-based stack, use the end of the array as the top. As shown below, pushing and popping correspond to adding and removing the last element, both taking $O(1)$ time.
=== "<1>"
![Push and pop operations in array implementation of stack](stack.assets/array_stack_step1.png)
![Push and pop in an array-based stack](stack.assets/array_stack_step1.png)
=== "<2>"
![array_stack_push](stack.assets/array_stack_step2_push.png)
@@ -393,38 +393,38 @@ When implementing a stack using an array, we can treat the end of the array as t
=== "<3>"
![array_stack_pop](stack.assets/array_stack_step3_pop.png)
Since elements pushed onto the stack may increase continuously, we can use a dynamic array, which eliminates the need to handle array expansion ourselves. Here is the sample code:
Since elements may keep arriving, use a dynamic array so that resizing is handled for us. An implementation follows:
```src
[file]{array_stack}-[class]{array_stack}-[func]{}
```
## Comparison of the Two Implementations
## Comparing the implementations
**Supported Operations**
**Supported operations**
Both implementations support all operations defined by the stack. The array implementation additionally supports random access, but this goes beyond the stack definition and is generally not used.
Both implementations support all stack operations. An array also allows random access, but that is outside the stack abstraction and is generally not used.
**Time Efficiency**
**Time efficiency**
In the array-based implementation, both push and pop operations occur in pre-allocated contiguous memory, which has good cache locality and is therefore more efficient. However, if pushing exceeds the array capacity, it triggers an expansion mechanism, causing the time complexity of that particular push operation to become $O(n)$.
In an array-based stack, pushes and pops operate in preallocated contiguous memory, giving good cache locality and high efficiency. However, a push that exceeds the array's capacity triggers expansion, making that particular push an $O(n)$ operation.
In the linked list-based implementation, list expansion is very flexible, and there is no issue of reduced efficiency due to array expansion. However, the push operation requires initializing a node object and modifying pointers, so it is relatively less efficient. Nevertheless, if the pushed elements are already node objects, the initialization step can be omitted, thereby improving efficiency.
A linked list grows flexibly and avoids the slowdown associated with array expansion. However, pushing requires creating a node object and updating pointers, so it is relatively slower. If the element is already a node object, the creation step can be skipped to improve efficiency.
In summary, when the elements pushed and popped are basic data types such as `int` or `double`, we can draw the following conclusions:
For elements of primitive types such as `int` or `double`, we can therefore draw the following conclusions.
- The array-based stack implementation has reduced efficiency when expansion is triggered, but since expansion is an infrequent operation, the average efficiency is higher.
- The linked list-based stack implementation can provide more stable efficiency performance.
- An array-based stack slows down when expansion is triggered, but expansion is infrequent, so average efficiency is higher.
- A linked-list stack provides more consistent performance.
**Space Efficiency**
**Space efficiency**
When initializing a list, the system allocates an "initial capacity" that may exceed the actual need. Additionally, the expansion mechanism typically expands at a specific ratio (e.g., 2x), and the capacity after expansion may also exceed actual needs. Therefore, **the array-based stack implementation may cause some space wastage**.
When a dynamic array is initialized, its initial capacity may exceed actual needs. Expansion typically multiplies the capacity by a fixed factor, such as 2, which may again leave excess space. **An array-based stack can therefore waste some space**.
However, since linked list nodes need to store additional pointers, **the space occupied by linked list nodes is relatively large**.
However, linked-list nodes also store pointers, **so each node occupies relatively more space**.
In summary, we cannot simply determine which implementation is more memory-efficient and need to analyze the specific situation.
We cannot say universally which implementation uses less memory; the answer depends on the situation.
## Typical Applications of Stack
## Typical applications
- **Back and forward in browsers, undo and redo in software**. Every time we open a new webpage, the browser pushes the previous page onto the stack, allowing us to return to the previous page via the back operation. The back operation is essentially performing a pop. To support both back and forward, two stacks are needed to work together.
- **Program memory management**. Each time a function is called, the system adds a stack frame to the top of the stack to record the function's context information. During recursion, the downward recursive phase continuously performs push operations, while the upward backtracking phase continuously performs pop operations.
- **Browser back and forward navigation, and software undo and redo**. When a new web page is opened, the browser pushes the previous page onto a stack. Going back pops that page. Supporting both back and forward requires two stacks working together.
- **Program memory management**. Each function call adds a stack frame containing the function's context. During recursion, frames are pushed as calls descend and popped as they return.

View File

@@ -1,31 +1,31 @@
# Summary
### Key Review
### Key takeaways
- A stack is a data structure that follows the LIFO principle and can be implemented using arrays or linked lists.
- In terms of time efficiency, the array implementation of a stack has higher average efficiency, but during expansion, the time complexity of a single push operation degrades to $O(n)$. In contrast, the linked-list implementation of a stack offers more stable performance.
- In terms of space efficiency, the array implementation of a stack may lead to some degree of space wastage. However, it should be noted that the memory space occupied by linked list nodes is larger than that of array elements.
- A queue is a data structure that follows the FIFO principle and can also be implemented using arrays or linked lists. The conclusions regarding time efficiency and space efficiency comparisons for queues are similar to those for stacks mentioned above.
- A deque is a queue with greater flexibility that allows adding and removing elements at both ends.
- A stack follows last-in, first-out order and can be implemented with an array or linked list.
- An array-based stack offers higher average time efficiency, but a push that triggers expansion takes $O(n)$ time. A linked-list stack provides more consistent performance.
- An array-based stack may waste some space. However, linked-list nodes require more memory than individual array elements.
- A queue follows first-in, first-out order and can also be implemented with an array or linked list. Their time and space tradeoffs resemble those of stack implementations.
- A deque is a more flexible queue that allows insertion and removal at both ends.
### Q & A
**Q**: Is the browser's forward and backward functionality implemented with a doubly linked list?
**Q**: Are browser back and forward navigation implemented with a doubly linked list?
The browser's forward and backward behavior is essentially an application of a "stack." When a user visits a new page, that page is added to the top of the stack; when the user clicks the back button, that page is popped from the top of the stack. A deque can conveniently support some additional operations, as mentioned in the "Deque" section.
Browser navigation fundamentally reflects stack behavior. Visiting a new page adds it to the top of a stack; clicking Back removes it. A deque conveniently supports additional operations, as discussed in the deque section.
**Q**: After popping from the stack, do we need to free the memory of the popped node?
**Q**: After popping a node, do we need to free its memory?
If the popped node will still be needed later, then memory does not need to be freed. If it won't be used afterward, languages like Java and Python have automatic garbage collection, so manual memory deallocation is not required; in C and C++, manual memory deallocation is necessary.
If the node will still be used, do not free it. If it is no longer needed, languages such as `Java` and `Python` use automatic garbage collection, so manual deallocation is unnecessary. In `C` and `C++`, memory must be released manually.
**Q**: A deque seems like two stacks joined together. What is its purpose?
**Q**: A deque looks like two stacks joined together. What is it useful for?
A deque is like a combination of a stack and a queue, or two stacks joined together. It combines the logic of both, so it can support all applications of stacks and queues while offering greater flexibility.
A deque resembles a combination of a stack and a queue, or two stacks joined together. It combines stack and queue behavior, supporting all their applications with greater flexibility.
**Q**: How are undo and redo specifically implemented?
**Q**: How exactly do undo and redo work?
Use two stacks: stack `A` for undo and stack `B` for redo.
Use two stacks: `A` for undo and `B` for redo.
1. Whenever the user performs an operation, push this operation onto stack `A` and clear stack `B`.
2. When the user performs "undo," pop the most recent operation from stack `A` and push it onto stack `B`.
3. When the user performs "redo," pop the most recent operation from stack `B` and push it onto stack `A`.
1. Whenever the user performs an action, push it onto `A` and clear `B`.
2. To undo, pop the most recent action from `A` and push it onto `B`.
3. To redo, pop the most recent action from `B` and push it onto `A`.