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,19 +1,19 @@
# Array
# Arrays
An <u>array</u> is a linear data structure that stores elements of the same type in contiguous memory space. The position of an element in the array is called the element's <u>index</u>. The figure below illustrates the main concepts and storage method of arrays.
An <u>array</u> is a linear data structure that stores elements of the same type in contiguous memory. An element's position in the array is its <u>index</u>. The figure below shows the main concepts and storage layout.
![Array definition and storage method](array.assets/array_definition.png)
![Array definition and storage layout](array.assets/array_definition.png)
## Common Array Operations
## Common array operations
### Initializing Arrays
### Initializing an array
We can choose between two array initialization methods based on our needs: with or without initial values. When no initial values are specified, most programming languages initialize array elements to $0$:
We can initialize an array with or without explicit values. When values are not specified, most programming languages initialize the elements to $0$:
=== "Python"
```python title="array.py"
# Initialize array
# Initialize arrays
arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ]
nums: list[int] = [1, 3, 2, 5, 4]
```
@@ -21,11 +21,11 @@ We can choose between two array initialization methods based on our needs: with
=== "C++"
```cpp title="array.cpp"
/* Initialize array */
// Stored on stack
/* Initialize arrays */
// Stored on the stack
int arr[5] = {};
int nums[5] = { 1, 3, 2, 5, 4 };
// Stored on heap (requires manual memory release)
// Stored on the heap (memory must be freed manually)
int* arr1 = new int[5] {};
int* nums1 = new int[5] { 1, 3, 2, 5, 4 };
```
@@ -33,7 +33,7 @@ We can choose between two array initialization methods based on our needs: with
=== "Java"
```java title="array.java"
/* Initialize array */
/* Initialize arrays */
int[] arr = new int[5]; // { 0, 0, 0, 0, 0 }
int[] nums = { 1, 3, 2, 5, 4 };
```
@@ -41,7 +41,7 @@ We can choose between two array initialization methods based on our needs: with
=== "C#"
```csharp title="array.cs"
/* Initialize array */
/* Initialize arrays */
int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ]
int[] nums = [1, 3, 2, 5, 4];
```
@@ -49,18 +49,18 @@ We can choose between two array initialization methods based on our needs: with
=== "Go"
```go title="array.go"
/* Initialize array */
/* Initialize arrays */
var arr [5]int
// In Go, specifying length ([5]int) creates an array; not specifying length ([]int) creates a slice
// Since Go's arrays are designed to have their length determined at compile time, only constants can be used to specify the length
// For convenience in implementing the extend() method, slices are treated as arrays below
// In Go, [5]int is an array with a specified length; []int is a slice
// Go array lengths are determined at compile time and must be constants
// To make extend() easier to implement, we treat slices as arrays below
nums := []int{1, 3, 2, 5, 4}
```
=== "Swift"
```swift title="array.swift"
/* Initialize array */
/* Initialize arrays */
let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0]
let nums = [1, 3, 2, 5, 4]
```
@@ -68,7 +68,7 @@ We can choose between two array initialization methods based on our needs: with
=== "JS"
```javascript title="array.js"
/* Initialize array */
/* Initialize arrays */
var arr = new Array(5).fill(0);
var nums = [1, 3, 2, 5, 4];
```
@@ -76,7 +76,7 @@ We can choose between two array initialization methods based on our needs: with
=== "TS"
```typescript title="array.ts"
/* Initialize array */
/* Initialize arrays */
let arr: number[] = new Array(5).fill(0);
let nums: number[] = [1, 3, 2, 5, 4];
```
@@ -84,7 +84,7 @@ We can choose between two array initialization methods based on our needs: with
=== "Dart"
```dart title="array.dart"
/* Initialize array */
/* Initialize arrays */
List<int> arr = List.filled(5, 0); // [0, 0, 0, 0, 0]
List<int> nums = [1, 3, 2, 5, 4];
```
@@ -92,20 +92,20 @@ We can choose between two array initialization methods based on our needs: with
=== "Rust"
```rust title="array.rs"
/* Initialize array */
/* Initialize arrays */
let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0]
let slice: &[i32] = &[0; 5];
// In Rust, specifying length ([i32; 5]) creates an array; not specifying length (&[i32]) creates a slice
// Since Rust's arrays are designed to have their length determined at compile time, only constants can be used to specify the length
// Vector is the type generally used as a dynamic array in Rust
// For convenience in implementing the extend() method, vectors are treated as arrays below
// In Rust, [i32; 5] is an array with a specified length; &[i32] is a slice
// Rust array lengths are determined at compile time and must be constants
// Vector is Rust's usual dynamic array type
// To make extend() easier to implement, we treat a vector as an array below
let nums: Vec<i32> = vec![1, 3, 2, 5, 4];
```
=== "C"
```c title="array.c"
/* Initialize array */
/* Initialize arrays */
int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 }
int nums[5] = { 1, 3, 2, 5, 4 };
```
@@ -113,7 +113,7 @@ We can choose between two array initialization methods based on our needs: with
=== "Kotlin"
```kotlin title="array.kt"
/* Initialize array */
/* Initialize arrays */
var arr = IntArray(5) // { 0, 0, 0, 0, 0 }
var nums = intArrayOf(1, 3, 2, 5, 4)
```
@@ -121,107 +121,107 @@ We can choose between two array initialization methods based on our needs: with
=== "Ruby"
```ruby title="array.rb"
# Initialize array
# Initialize arrays
arr = Array.new(5, 0)
nums = [1, 3, 2, 5, 4]
```
??? pythontutor "Code Visualization"
??? pythontutor "Visualize execution"
https://pythontutor.com/render.html#code=%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E6%95%B0%E7%BB%84%0Aarr%20%3D%20%5B0%5D%20*%205%20%20%23%20%5B%200,%200,%200,%200,%200%20%5D%0Anums%20%3D%20%5B1,%203,%202,%205,%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=%23%20Initialize%20arrays%0Aarr%20%3D%20%5B0%5D%20%2A%205%20%20%23%20%5B%200%2C%200%2C%200%2C%200%2C%200%20%5D%0Anums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
### Accessing Elements
### Accessing an element
Array elements are stored in contiguous memory space, which means calculating the memory address of array elements is very easy. Given the array's memory address (the memory address of the first element) and an element's index, we can use the formula shown in the figure below to calculate the element's memory address and directly access that element.
Because array elements occupy contiguous memory, their addresses are easy to calculate. Given the array's address (the address of its first element) and an index, the formula in the figure below gives the element's address, allowing direct access.
![Memory address calculation for array elements](array.assets/array_memory_location_calculation.png)
![Calculating an array element's memory address](array.assets/array_memory_location_calculation.png)
Observing the figure above, we find that the first element of an array has an index of $0$, which may seem counterintuitive since counting from $1$ would be more natural. However, from the perspective of the address calculation formula, **an index is essentially an offset from the memory address**. The address offset of the first element is $0$, so it is reasonable for its index to be $0$.
The first element has index $0$, which may seem unintuitive because counting from $1$ feels more natural. However, **an index essentially describes an offset from the starting memory address**. The first element's offset is $0$, so index $0$ makes sense.
Accessing elements in an array is highly efficient; we can randomly access any element in the array in $O(1)$ time.
Array access is very efficient: any element can be accessed directly in $O(1)$ time.
```src
[file]{array}-[class]{}-[func]{random_access}
```
### Inserting Elements
### Inserting an element
Array elements are packed tightly together in memory, with no extra space between them for additional data. As shown in the figure below, if we want to insert an element in the middle of an array, we need to shift all subsequent elements one position to the right and then assign the value at that index.
Array elements sit next to one another, with no room between them for more data. As shown in the figure below, inserting into the middle requires shifting every element at or after the insertion point one position toward the end, then assigning the new element at the desired index.
![Example of inserting an element into an array](array.assets/array_insert_element.png)
![Inserting an element into an array](array.assets/array_insert_element.png)
It is worth noting that since the length of an array is fixed, inserting an element will inevitably push the last element out of the array. We will leave the solution to this problem for discussion in the "List" chapter.
Because an array's length is fixed, inserting an element causes the last element to be lost. We will discuss the solution in the section on lists.
```src
[file]{array}-[class]{}-[func]{insert}
```
### Removing Elements
### Removing an element
Similarly, as shown in the figure below, to delete the element at index $i$, we need to shift all elements after index $i$ forward by one position.
Similarly, as shown in the figure below, removing the element at index $i$ requires shifting every element after $i$ one position toward the beginning.
![Example of removing an element from an array](array.assets/array_remove_element.png)
![Removing an element from an array](array.assets/array_remove_element.png)
Note that after the deletion is complete, the original last element is no longer meaningful, so we do not need to modify it explicitly.
After removal, the old final entry is no longer meaningful, so we do not need to change it explicitly.
```src
[file]{array}-[class]{}-[func]{remove}
```
Overall, array insertion and deletion operations have the following drawbacks:
Overall, inserting and removing array elements have these drawbacks.
- **High time complexity**: The average time complexity for both insertion and deletion in arrays is $O(n)$, where $n$ is the length of the array.
- **Loss of elements**: Since the length of an array is immutable, after inserting an element, elements that exceed the array's length will be lost.
- **Memory waste**: We can initialize a relatively long array and use only the front portion, so that any overwritten tail elements are merely unused placeholders, but this wastes some memory space.
- **High time complexity**: Both operations take $O(n)$ time on average, where $n$ is the array length.
- **Lost elements**: Since the length is fixed, insertion loses any element pushed beyond the array's bounds.
- **Wasted memory**: We can allocate a longer array and use only its beginning, so any final entries lost during insertion are unused. However, this leaves some memory wasted.
### Traversing Arrays
### Traversing an array
In most programming languages, we can traverse an array either by index or by directly iterating through each element in the array:
Most programming languages let us traverse an array either by index or by visiting its elements directly:
```src
[file]{array}-[class]{}-[func]{traverse}
```
### Finding Elements
### Finding an element
Finding a specified element in an array requires traversing the array and checking whether the element value matches in each iteration; if it matches, output the corresponding index.
To find a specified element, traverse the array and compare each value with the target. Return the index when a match is found.
Since an array is a linear data structure, the above search operation is called a "linear search".
Because an array is a linear data structure, this is called linear search.
```src
[file]{array}-[class]{}-[func]{find}
```
### Expanding Arrays
### Expanding an array
In complex system environments, programs cannot guarantee that the memory space after an array is available, making it unsafe to expand the array's capacity. Therefore, in most programming languages, **the length of an array is immutable**.
In a complex system, a program cannot ensure that memory immediately after an array is available, so extending it in place is unsafe. Therefore, in most programming languages, **an array's length is fixed**.
If we want to expand an array, we need to create a new, larger array and then copy the original array elements to the new array one by one. This is an $O(n)$ operation, which is very time-consuming when the array is large. The code is shown below:
To expand an array, create a larger one and copy every element into it. This takes $O(n)$ time and can be expensive for a large array. The code is as follows:
```src
[file]{array}-[class]{}-[func]{extend}
```
## Advantages and Limitations of Arrays
## Strengths and limitations of arrays
Arrays are stored in contiguous memory space with elements of the same type. This approach contains rich prior information that the system can use to optimize the efficiency of data structure operations.
An array stores elements of one type in contiguous memory. These known properties give the system opportunities to optimize operations.
- **High space efficiency**: Arrays allocate contiguous memory blocks for data without additional structural overhead.
- **Support for random access**: Arrays allow accessing any element in $O(1)$ time.
- **Cache locality**: When accessing array elements, the computer not only loads the element but also caches the surrounding data, thereby leveraging the cache to improve the execution speed of subsequent operations.
- **Space efficiency**: Data occupies a contiguous block with no extra structural overhead.
- **Random access**: Any element can be accessed in $O(1)$ time.
- **Cache locality**: Accessing an element loads not only that element but also nearby data into the cache, speeding up later operations.
Contiguous space storage is a double-edged sword with the following limitations:
Contiguous storage also has limitations.
- **Low insertion and deletion efficiency**: When an array has many elements, insertion and deletion operations require shifting a large number of elements.
- **Immutable length**: After an array is initialized, its length is fixed. Expanding the array requires copying all data to a new array, which is very costly.
- **Space waste**: If the allocated size of an array exceeds what is actually needed, the extra space is wasted.
- **Slow insertion and deletion**: With many elements, these operations require substantial shifting.
- **Fixed length**: Once initialized, an array cannot change length; expansion requires copying all data into a new array.
- **Wasted space**: Any allocated space beyond actual needs is unused.
## Typical Applications of Arrays
## Typical applications of arrays
Arrays are a fundamental and common data structure, frequently used in various algorithms and for implementing various complex data structures.
Arrays are fundamental, widely used data structures. They appear throughout algorithms and underpin more complex structures.
- **Random access**: If we want to randomly sample some items, we can use an array to store them and generate a random sequence to implement random sampling based on indices.
- **Sorting and searching**: Arrays are the most commonly used data structure for sorting and searching algorithms. Quick sort, merge sort, binary search, and others are primarily performed on arrays.
- **Lookup tables**: When we need to quickly find an element or its corresponding relationship, we can use an array as a lookup table. For example, if we want to implement a mapping from characters to ASCII codes, we can use the ASCII code value of a character as an index, with the corresponding element stored at that position in the array.
- **Machine learning**: Neural networks make extensive use of linear algebra operations between vectors, matrices, and tensors, all of which are constructed in the form of arrays. Arrays are the most commonly used data structure in neural network programming.
- **Data structure implementation**: Arrays can be used to implement stacks, queues, hash tables, heaps, graphs, and other data structures. For example, the adjacency matrix representation of a graph is essentially a two-dimensional array.
- **Random access**: To draw random samples, store data in an array and generate random indices to select elements.
- **Sorting and searching**: Arrays are the most common structures for these algorithms. Quick sort, merge sort, and binary search operate primarily on arrays.
- **Lookup tables**: An array can provide fast access to an element or a mapping. For example, a character-to-ASCII mapping can use a character's ASCII value as an index and store its corresponding element there.
- **Machine learning**: Neural networks make extensive use of linear algebra on vectors, matrices, and tensors, all built from arrays. Arrays are the most common data structure in neural network programming.
- **Implementing data structures**: Arrays can implement stacks, queues, hash tables, heaps, graphs, and more. A graph's adjacency matrix, for example, is a two-dimensional array.

View File

@@ -1,106 +1,106 @@
# Exercises
## Concept Review
## Check your understanding
### How Arrays and Linked Lists Find an Element
### Finding elements in arrays and linked lists
An array and a singly linked list both store `[A, B, C, D, E]` in order. You now need to access the fourth element, `D`:
An array and a singly linked list both store `[A, B, C, D, E]` in order. We want to read the fourth element, `D`:
<!-- numbered-subquestions -->
1. Which index can the array use directly?
2. Starting from the head node `A`, which nodes are visited in order as you follow `next`?
3. As the requested element moves farther toward the end, how does the number of steps change for each structure? Which structure is better for repeated access by position, and why?
1. Which index can we use to access it directly in the array?
2. Starting at the head node `A`, which nodes must the singly linked list visit by following `next`?
3. As the requested element moves farther toward the end, how does the number of steps change for each structure? Which is better suited to repeated access by position, and why?
??? success "Answer"
??? success "Reference answer"
1. With zero-based indexing, the fourth element has index 3, so the array can access `arr[3]` directly.
1. With zero-based indexing, the fourth element has index 3, so the array can read `arr[3]` directly.
2. The singly linked list must start at the head. Its access path is `A → B → C → D`, requiring three moves through `next`.
2. The singly linked list must start at the head and follow the path `A → B → C → D`, advancing along `next` three times.
3. An array can locate an element directly from its starting address and index, so access by position has a time complexity of $O(1)$.
To access the $k$th node, a singly linked list must start at the head node and follow `next` $k-1$ times,
which takes $O(n)$ time in the worst case.
3. An array can locate an element directly from its starting address and the index, giving time complexity $O(1)$ for access by position.
To access the $k$-th node of a singly linked list, we must start at the head and follow `next` $k-1$ times,
taking $O(n)$ time in the worst case.
This comparison concerns only access by position; it does not mean that linked lists are slower for every operation.
This comparison concerns access by position only; it does not mean that linked lists are slower for every operation.
### How Arrays and Linked Lists Insert an Element
### Inserting elements into arrays and linked lists
An array and a singly linked list both store `A, B, C, D`. You now need to insert `X` after `B`:
An array and a singly linked list both store `A, B, C, D`. We want to insert `X` after `B`:
- The array has capacity 5 and is currently `[A, B, C, D, _]`.
- The linked list is `A → B → C → D`, and you already have a reference to node `B`.
- The array has capacity 5 and currently contains `[A, B, C, D, _]`.
- The linked list is `A → B → C → D`, and we already have a reference to node `B`.
<!-- numbered-subquestions -->
1. Which elements must the array move? Write the array after insertion.
2. In what order should the linked list update `X.next` and `B.next`? Write the linked list after insertion.
3. When comparing insertion efficiency, why is it important to state that "you already have a reference to node B"?
1. Which elements must the array move? Write out the array after insertion.
2. In what order should the linked list update `X.next` and `B.next`? Write out the resulting list.
3. Why must a comparison of insertion efficiency specify that we already have a reference to node B?
??? success "Answer"
??? success "Reference answer"
1. The array first moves `D` one position to the right, then moves `C` one position to the right, and finally places `X` at index 2,
producing `[A, B, X, C, D]`.
1. First move `D` one position to the right, then move `C` one position to the right, and finally put `X` at index 2.
The result is `[A, B, X, C, D]`.
2. `B.next` originally points to `C`. First set `X.next = B.next`, making `X` point to `C`;
then set `B.next = X`. The result is `A → B → X → C → D`.
If `B.next` is overwritten first without saving the original link, `C` may become unreachable.
2. Initially, `B.next` points to `C`. First set `X.next = B.next`, making `X` point to `C`.
Then set `B.next = X`. The result is `A → B → X → C → D`.
If we overwrite `B.next` first without saving the original link, we may lose access to `C`.
3. Once the location of `B` is known, insertion into the linked list only changes two links and takes $O(1)$ time.
If `B` must first be found from the head, that search alone may take $O(n)$ time.
3. Once the location of `B` is known, insertion into the linked list requires changing only two links and takes $O(1)$ time.
If we first need to search for `B` from the head, that search itself may take $O(n)$ time.
### How a List's Capacity Grows
### How does a list's capacity grow?
An array-based list currently contains `[A, B, C]`, with length `size = 3` and capacity `capacity = 4`.
When there is not enough capacity, a new array with twice the old capacity is created.
When capacity runs out, the new array is allocated with twice the previous capacity.
<!-- numbered-subquestions -->
1. After appending `D`, what are the list's length and capacity? Is capacity expansion needed?
1. After appending `D`, what are the list's length and capacity? Does it need to grow?
2. When `E` is appended next, what does the capacity become? How many existing elements must be copied?
3. The length of the underlying array cannot change. Why does the list's capacity nevertheless appear able to grow?
3. If the length of the underlying array cannot change, why does the list's capacity appear to grow?
??? success "Answer"
??? success "Reference answer"
1. `D` fits in the last empty position. The contents are now `[A, B, C, D]`,
with `size = 4` and `capacity = 4`, so no capacity expansion is needed.
1. `D` fits in the last empty position. The contents become `[A, B, C, D]`,
with `size = 4` and `capacity = 4`. No capacity increase is needed.
2. There is no empty position when `E` is appended, so a new array with capacity 8 must be created.
The four existing elements `A, B, C, D` are copied into it before `E` is added.
The result is `size = 5` and `capacity = 8`.
2. Appending `E` finds no empty position, so a new array of capacity 8 is created.
The four existing elements `A, B, C, D` are copied into it, and then `E` is added.
The list now has `size = 5` and `capacity = 8`.
3. The original array itself does not grow. The list creates a larger new array, copies the existing elements,
and then uses the new array as its underlying storage. From the user's perspective, the capacity has grown.
3. The original array itself does not become longer. The list creates a larger array, copies the existing elements,
and switches to using the new array for storage. From the user's perspective, its capacity has grown.
## Programming Exercises
## Programming exercises
### Add One to a Large Integer Stored as an Array
### Adding one to a large integer stored in an array
The array `digits` stores the decimal digits of a non-negative integer from left to right. For example, `[3, 0, 8]` represents 308.
The number 0 is represented by `[0]`; for every other input, the first digit is not 0.
The array `digits` stores the digits of a nonnegative integer from left to right. For example, `[3, 0, 8]` represents 308.
Zero is represented by `[0]`; all other inputs have a nonzero first digit.
Simulate decimal column addition to add 1 to this integer, and return the result in the same array format.
You may modify `digits` directly. If a new carry appears at the front, you may return a longer array.
Simulate the usual digit-by-digit method for decimal addition to add 1 to this integer, and return the result in the same array format.
You may modify `digits` directly. If a carry creates a new leading digit, you may return a longer array.
??? tip "Hints"
1. Start with the last digit of the array, just as in ordinary column addition
2. If the current digit is less than 9, add one and return immediately
3. If the current digit is 9, change it to 0; if every digit is 9, place a 1 at the front
1. Start at the last digit of the array, just as you would when adding by hand.
2. If the current digit is less than 9, increment it and return immediately.
3. If the current digit is 9, change it to 0. If all digits are 9, add a leading 1.
[LeetCode](https://leetcode.com/problems/plus-one/){ .rounded-button .exercise-button target="_blank" rel="noopener noreferrer" }
### Reverse a Singly Linked List
### Reversing a singly linked list
You are given the head node `head` of a singly linked list. Each node contains a value and a `next` reference to the following node.
Use an iterative approach to reverse all links between the nodes, and return the new head node.
Do not create any new linked list nodes.
Use iteration to reverse every link between nodes, and return the new head.
Do not create any new linked-list nodes.
??? tip "Hints"
1. First draw three connected nodes and the two pointers prev and cur on paper
2. Before changing cur.next, save the original next node in nxt
3. After reversing cur.next, set prev = cur and then cur = nxt to continue with the next node in the original list
1. First draw three connected nodes and the two pointers prev and cur on paper.
2. Before changing cur.next, save the original next node in nxt.
3. After reversing cur.next, set prev = cur and then cur = nxt to continue with the next node in the original list.
[LeetCode](https://leetcode.com/problems/reverse-linked-list/){ .rounded-button .exercise-button target="_blank" rel="noopener noreferrer" }

View File

@@ -1,9 +1,9 @@
# Arrays and Linked Lists
# Arrays and linked lists
![Arrays and Linked Lists](../assets/covers/chapter_array_and_linkedlist.jpg)
![Arrays and linked lists](../assets/covers/chapter_array_and_linkedlist.jpg)
!!! abstract
The world of data structures is like a solid brick wall.
The bricks of an array are neatly aligned, each pressed tightly against the next. The bricks of a linked list are scattered about, with connecting vines weaving freely through the gaps between them.
In an array, the bricks line up neatly, each right beside the next. In a linked list, the bricks are scattered, with connecting vines weaving freely through the gaps.

View File

@@ -1,20 +1,20 @@
# Linked List
# Linked lists
Memory is a shared resource for all programs. In a complex runtime environment, free memory may be scattered throughout the address space. We know that arrays require contiguous memory, and when an array is very large, the system may not be able to provide such a large contiguous block. This is where the flexibility of linked lists becomes apparent.
Memory is a resource used by all programs, and in a complex system, free space may be scattered throughout it. An array requires contiguous storage, which may be unavailable for a very large array. This is where a linked list's flexibility helps.
A <u>linked list</u> is a linear data structure in which each element is a node object, and the nodes are connected through "references". A reference records the memory address of the next node, through which the next node can be accessed from the current node.
A <u>linked list</u> is a linear data structure whose elements are node objects connected by references. Each reference stores the next node's memory address, allowing us to reach it from the current node.
This design allows linked-list nodes to be stored in different locations in memory, and their addresses do not need to be contiguous.
This design lets nodes occupy scattered memory locations; their addresses need not be contiguous.
![Linked list definition and storage method](linked_list.assets/linkedlist_definition.png)
![Linked list definition and storage layout](linked_list.assets/linkedlist_definition.png)
Observing the figure above, the basic unit of a linked list is a <u>node</u> object. Each node contains two pieces of data: the node's "value" and a "reference" to the next node.
As shown above, the basic unit of a linked list is a <u>node</u> object. Each node holds a value and a reference to the next node.
- The first node of a linked list is called the "head node", and the last node is called the "tail node".
- The tail node points to "null", which is denoted as `null`, `nullptr`, and `None` in Java, C++, and Python, respectively.
- In languages that support pointers, such as C, C++, Go, and Rust, the aforementioned "reference" should be replaced with "pointer".
- The first node is called the head, and the last is called the tail.
- The tail points to a null value: `null` in Java, `nullptr` in C++, and `None` in Python.
- In languages supporting pointers, such as C, C++, Go, and Rust, these references are expressed as pointers.
As shown in the following code, a linked list node `ListNode` contains not only a value but also an additional reference (pointer). Therefore, **linked lists occupy more memory space than arrays when storing the same amount of data**.
As the code below shows, each `ListNode` stores a reference (pointer) in addition to its value. Thus, **a linked list uses more memory than an array for the same amount of data**.
=== "Python"
@@ -67,7 +67,7 @@ As shown in the following code, a linked list node `ListNode` contains not only
Next *ListNode // Pointer to the next node
}
// NewListNode Constructor, creates a new linked list
// NewListNode constructor: create a new linked list
func NewListNode(val int) *ListNode {
return &ListNode{
Val: val,
@@ -185,23 +185,23 @@ As shown in the following code, a linked list node `ListNode` contains not only
end
```
## Common Linked List Operations
## Common linked list operations
### Initializing a Linked List
### Initializing a linked list
Building a linked list involves two steps: first, initializing each node object; second, constructing the reference relationships between nodes. Once initialization is complete, we can traverse all nodes starting from the head node of the linked list through the reference `next`.
Building a linked list takes two steps: initialize the node objects, then connect them with references. Afterward, start at the head and follow `next` references to visit every node in order.
=== "Python"
```python title="linked_list.py"
# Initialize linked list 1 -> 3 -> 2 -> 5 -> 4
# Initialize each node
# Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4
# Initialize the nodes
n0 = ListNode(1)
n1 = ListNode(3)
n2 = ListNode(2)
n3 = ListNode(5)
n4 = ListNode(4)
# Build references between nodes
# Link the nodes with references
n0.next = n1
n1.next = n2
n2.next = n3
@@ -211,14 +211,14 @@ Building a linked list involves two steps: first, initializing each node object;
=== "C++"
```cpp title="linked_list.cpp"
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize each node
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
ListNode* n0 = new ListNode(1);
ListNode* n1 = new ListNode(3);
ListNode* n2 = new ListNode(2);
ListNode* n3 = new ListNode(5);
ListNode* n4 = new ListNode(4);
// Build references between nodes
// Link the nodes with references
n0->next = n1;
n1->next = n2;
n2->next = n3;
@@ -228,14 +228,14 @@ Building a linked list involves two steps: first, initializing each node object;
=== "Java"
```java title="linked_list.java"
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize each node
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
ListNode n0 = new ListNode(1);
ListNode n1 = new ListNode(3);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(5);
ListNode n4 = new ListNode(4);
// Build references between nodes
// Link the nodes with references
n0.next = n1;
n1.next = n2;
n2.next = n3;
@@ -245,14 +245,14 @@ Building a linked list involves two steps: first, initializing each node object;
=== "C#"
```csharp title="linked_list.cs"
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize each node
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
ListNode n0 = new(1);
ListNode n1 = new(3);
ListNode n2 = new(2);
ListNode n3 = new(5);
ListNode n4 = new(4);
// Build references between nodes
// Link the nodes with references
n0.next = n1;
n1.next = n2;
n2.next = n3;
@@ -262,14 +262,14 @@ Building a linked list involves two steps: first, initializing each node object;
=== "Go"
```go title="linked_list.go"
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize each node
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
n0 := NewListNode(1)
n1 := NewListNode(3)
n2 := NewListNode(2)
n3 := NewListNode(5)
n4 := NewListNode(4)
// Build references between nodes
// Link the nodes with references
n0.Next = n1
n1.Next = n2
n2.Next = n3
@@ -279,14 +279,14 @@ Building a linked list involves two steps: first, initializing each node object;
=== "Swift"
```swift title="linked_list.swift"
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize each node
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
let n0 = ListNode(x: 1)
let n1 = ListNode(x: 3)
let n2 = ListNode(x: 2)
let n3 = ListNode(x: 5)
let n4 = ListNode(x: 4)
// Build references between nodes
// Link the nodes with references
n0.next = n1
n1.next = n2
n2.next = n3
@@ -296,14 +296,14 @@ Building a linked list involves two steps: first, initializing each node object;
=== "JS"
```javascript title="linked_list.js"
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize each node
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
const n0 = new ListNode(1);
const n1 = new ListNode(3);
const n2 = new ListNode(2);
const n3 = new ListNode(5);
const n4 = new ListNode(4);
// Build references between nodes
// Link the nodes with references
n0.next = n1;
n1.next = n2;
n2.next = n3;
@@ -313,14 +313,14 @@ Building a linked list involves two steps: first, initializing each node object;
=== "TS"
```typescript title="linked_list.ts"
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize each node
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
const n0 = new ListNode(1);
const n1 = new ListNode(3);
const n2 = new ListNode(2);
const n3 = new ListNode(5);
const n4 = new ListNode(4);
// Build references between nodes
// Link the nodes with references
n0.next = n1;
n1.next = n2;
n2.next = n3;
@@ -330,14 +330,14 @@ Building a linked list involves two steps: first, initializing each node object;
=== "Dart"
```dart title="linked_list.dart"
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */\
// Initialize each node
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */\
// Initialize the nodes
ListNode n0 = ListNode(1);
ListNode n1 = ListNode(3);
ListNode n2 = ListNode(2);
ListNode n3 = ListNode(5);
ListNode n4 = ListNode(4);
// Build references between nodes
// Link the nodes with references
n0.next = n1;
n1.next = n2;
n2.next = n3;
@@ -347,15 +347,15 @@ Building a linked list involves two steps: first, initializing each node object;
=== "Rust"
```rust title="linked_list.rs"
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize each node
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None }));
let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None }));
let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None }));
let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None }));
let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None }));
// Build references between nodes
// Link the nodes with references
n0.borrow_mut().next = Some(n1.clone());
n1.borrow_mut().next = Some(n2.clone());
n2.borrow_mut().next = Some(n3.clone());
@@ -365,14 +365,14 @@ Building a linked list involves two steps: first, initializing each node object;
=== "C"
```c title="linked_list.c"
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize each node
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
ListNode* n0 = newListNode(1);
ListNode* n1 = newListNode(3);
ListNode* n2 = newListNode(2);
ListNode* n3 = newListNode(5);
ListNode* n4 = newListNode(4);
// Build references between nodes
// Link the nodes with references
n0->next = n1;
n1->next = n2;
n2->next = n3;
@@ -382,14 +382,14 @@ Building a linked list involves two steps: first, initializing each node object;
=== "Kotlin"
```kotlin title="linked_list.kt"
/* Initialize linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize each node
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
val n0 = ListNode(1)
val n1 = ListNode(3)
val n2 = ListNode(2)
val n3 = ListNode(5)
val n4 = ListNode(4)
// Build references between nodes
// Link the nodes with references
n0.next = n1;
n1.next = n2;
n2.next = n3;
@@ -399,88 +399,88 @@ Building a linked list involves two steps: first, initializing each node object;
=== "Ruby"
```ruby title="linked_list.rb"
# Initialize linked list 1 -> 3 -> 2 -> 5 -> 4
# Initialize each node
# Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4
# Initialize the nodes
n0 = ListNode.new(1)
n1 = ListNode.new(3)
n2 = ListNode.new(2)
n3 = ListNode.new(5)
n4 = ListNode.new(4)
# Build references between nodes
# Link the nodes with references
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
```
??? pythontutor "Code Visualization"
??? pythontutor "Visualize execution"
https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%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%93%BE%E8%A1%A8%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%90%84%E4%B8%AA%E8%8A%82%E7%82%B9%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&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=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked%20list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20successor%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%20the%20linked%20list%201%20-%3E%203%20-%3E%202%20-%3E%205%20-%3E%204%0A%20%20%20%20%23%20Initialize%20the%20nodes%0A%20%20%20%20n0%20%3D%20ListNode%281%29%0A%20%20%20%20n1%20%3D%20ListNode%283%29%0A%20%20%20%20n2%20%3D%20ListNode%282%29%0A%20%20%20%20n3%20%3D%20ListNode%285%29%0A%20%20%20%20n4%20%3D%20ListNode%284%29%0A%20%20%20%20%23%20Link%20the%20nodes%20with%20references%0A%20%20%20%20n0.next%20%3D%20n1%0A%20%20%20%20n1.next%20%3D%20n2%0A%20%20%20%20n2.next%20%3D%20n3%0A%20%20%20%20n3.next%20%3D%20n4&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
An array is a single variable; for example, an array `nums` contains elements `nums[0]`, `nums[1]`, and so on. A linked list, by contrast, is composed of multiple independent node objects. **We usually use the head node as a stand-in for the entire linked list**; for example, the linked list in the above code can be referred to as linked list `n0`.
An array is a single variable, such as `nums`, containing entries `nums[0]`, `nums[1]`, and so on. A linked list consists of separate node objects. **We usually refer to the list by its head node**; for example, the list above can be called `n0`.
### Inserting a Node
### Inserting a node
Inserting a node in a linked list is very easy. As shown in the figure below, suppose we want to insert a new node `P` between two adjacent nodes `n0` and `n1`. **We only need to change two node references (pointers)**, with a time complexity of $O(1)$.
Inserting a node is straightforward. As shown in the figure below, inserting a new node `P` between adjacent nodes `n0` and `n1` **requires changing only two references (pointers)**, taking $O(1)$ time.
In contrast, the time complexity of inserting an element in an array is $O(n)$, which is inefficient when dealing with large amounts of data.
In contrast, inserting an array element takes $O(n)$ time and is slower for large datasets.
![Example of inserting a node into a linked list](linked_list.assets/linkedlist_insert_node.png)
![Inserting a node into a linked list](linked_list.assets/linkedlist_insert_node.png)
```src
[file]{linked_list}-[class]{}-[func]{insert}
```
### Removing a Node
### Removing a node
As shown in the figure below, removing a node in a linked list is also very convenient. **We only need to change one node's reference (pointer)**.
Removing a node is also straightforward: as shown in the figure below, **only one reference (pointer) needs to change**.
Note that although node `P` still points to `n1` after the deletion operation is complete, the linked list can no longer access `P` when traversing, which means `P` no longer belongs to this linked list.
Although `P` still points to `n1` after removal, traversing the list can no longer reach `P`. It therefore no longer belongs to the list.
![Removing a node from a linked list](linked_list.assets/linkedlist_remove_node.png)
![Removing a linked list node](linked_list.assets/linkedlist_remove_node.png)
```src
[file]{linked_list}-[class]{}-[func]{remove}
```
### Accessing a Node
### Accessing a node
**Accessing nodes in a linked list is less efficient**. As mentioned in the previous section, we can access any element in an array in $O(1)$ time. This is not the case with linked lists. The program needs to start from the head node and traverse backward one by one until the target node is found. That is, accessing the $i$-th node in a linked list requires $i - 1$ iterations, with a time complexity of $O(n)$.
**Accessing a node in a linked list is relatively slow**. An array provides access to any element in $O(1)$ time, but a linked list must be traversed from its head until the desired node is reached. Accessing the $i$-th node requires $i - 1$ iterations, giving $O(n)$ time complexity.
```src
[file]{linked_list}-[class]{}-[func]{access}
```
### Finding a Node
### Finding a node
Traverse the linked list to find a node with value `target`, and output the index of that node in the linked list. This process is also a linear search. The code is shown below:
Traverse the list to find a node with value `target`, then return its index. This is also linear search. The code is as follows:
```src
[file]{linked_list}-[class]{}-[func]{find}
```
## Arrays vs. Linked Lists
## Arrays versus linked lists
The table below summarizes the characteristics of arrays and linked lists and compares their operational efficiencies. Since they employ two opposite storage strategies, their various properties and operational efficiencies also exhibit contrasting characteristics.
The table below compares their properties and operation costs. Their contrasting storage strategies give them contrasting strengths.
<p align="center"> Table <id> &nbsp; Comparison of array and linked list efficiencies </p>
<p align="center"> Table <id> &nbsp; Comparing array and linked list efficiency </p>
| | Array | Linked List |
| ---------------------- | --------------------------------------------- | -------------------------- |
| Storage method | Contiguous memory space | Scattered memory space |
| Capacity expansion | Immutable length | Flexible expansion |
| Memory efficiency | Elements occupy less memory, but space may be wasted | Elements occupy more memory |
| Accessing an element | $O(1)$ | $O(n)$ |
| Adding an element | $O(n)$ | $O(1)$ |
| Removing an element | $O(n)$ | $O(1)$ |
| | Array | Linked list |
| -------- | ------------------------------ | -------------- |
| Storage | Contiguous memory | Scattered memory |
| Expansion | Fixed length | Flexible expansion |
| Memory efficiency | Less memory per element, but may waste space | More memory per element |
| Access an element | $O(1)$ | $O(n)$ |
| Add an element | $O(n)$ | $O(1)$ |
| Remove an element | $O(n)$ | $O(1)$ |
## Common Types of Linked Lists
## Common types of linked lists
As shown in the figure below, there are three common types of linked lists:
The figure below shows three common types.
- **Singly linked list**: This is the ordinary linked list introduced earlier. The nodes of a singly linked list contain a value and a reference to the next node. We call the first node the head node and the last node the tail node; the tail node points to `None`.
- **Circular linked list**: If we make the tail node of a singly linked list point to the head node (connecting the tail to the head), we get a circular linked list. In a circular linked list, any node can be viewed as the head node.
- **Doubly linked list**: Compared to a singly linked list, a doubly linked list records references in both directions. The node definition of a doubly linked list includes references to both the successor node (next node) and the predecessor node (previous node). Compared to a singly linked list, a doubly linked list is more flexible and can traverse the linked list in both directions, but it also requires more memory space.
- **Singly linked list**: The ordinary linked list introduced above. Each node stores a value and a reference to the next node. The first and last nodes are the head and tail, and the tail points to `None`.
- **Circular linked list**: Connecting a singly linked list's tail to its head forms a circular list. Any node can then be treated as the head.
- **Doubly linked list**: Each node stores references (pointers) in both directions, to its successor and predecessor. This makes it more flexible and allows traversal in either direction, at the cost of additional memory.
=== "Python"
@@ -489,8 +489,8 @@ As shown in the figure below, there are three common types of linked lists:
"""Doubly linked list node class"""
def __init__(self, val: int):
self.val: int = val # Node value
self.next: ListNode | None = None # Reference to the successor node
self.prev: ListNode | None = None # Reference to the predecessor node
self.next: ListNode | None = None # Reference to the successor
self.prev: ListNode | None = None # Reference to the predecessor
```
=== "C++"
@@ -499,8 +499,8 @@ As shown in the figure below, there are three common types of linked lists:
/* Doubly linked list node structure */
struct ListNode {
int val; // Node value
ListNode *next; // Pointer to the successor node
ListNode *prev; // Pointer to the predecessor node
ListNode *next; // Pointer to the successor
ListNode *prev; // Pointer to the predecessor
ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // Constructor
};
```
@@ -511,8 +511,8 @@ As shown in the figure below, there are three common types of linked lists:
/* Doubly linked list node class */
class ListNode {
int val; // Node value
ListNode next; // Reference to the successor node
ListNode prev; // Reference to the predecessor node
ListNode next; // Reference to the successor
ListNode prev; // Reference to the predecessor
ListNode(int x) { val = x; } // Constructor
}
```
@@ -523,8 +523,8 @@ As shown in the figure below, there are three common types of linked lists:
/* Doubly linked list node class */
class ListNode(int x) { // Constructor
int val = x; // Node value
ListNode next; // Reference to the successor node
ListNode prev; // Reference to the predecessor node
ListNode next; // Reference to the successor
ListNode prev; // Reference to the predecessor
}
```
@@ -534,11 +534,11 @@ As shown in the figure below, there are three common types of linked lists:
/* Doubly linked list node structure */
type DoublyListNode struct {
Val int // Node value
Next *DoublyListNode // Pointer to the successor node
Prev *DoublyListNode // Pointer to the predecessor node
Next *DoublyListNode // Pointer to the successor
Prev *DoublyListNode // Pointer to the predecessor
}
// NewDoublyListNode Initialization
// Initialize a node with NewDoublyListNode
func NewDoublyListNode(val int) *DoublyListNode {
return &DoublyListNode{
Val: val,
@@ -554,8 +554,8 @@ As shown in the figure below, there are three common types of linked lists:
/* Doubly linked list node class */
class ListNode {
var val: Int // Node value
var next: ListNode? // Reference to the successor node
var prev: ListNode? // Reference to the predecessor node
var next: ListNode? // Reference to the successor
var prev: ListNode? // Reference to the predecessor
init(x: Int) { // Constructor
val = x
@@ -570,8 +570,8 @@ As shown in the figure below, there are three common types of linked lists:
class ListNode {
constructor(val, next, prev) {
this.val = val === undefined ? 0 : val; // Node value
this.next = next === undefined ? null : next; // Reference to the successor node
this.prev = prev === undefined ? null : prev; // Reference to the predecessor node
this.next = next === undefined ? null : next; // Reference to the successor
this.prev = prev === undefined ? null : prev; // Reference to the predecessor
}
}
```
@@ -586,8 +586,8 @@ As shown in the figure below, there are three common types of linked lists:
prev: ListNode | null;
constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) {
this.val = val === undefined ? 0 : val; // Node value
this.next = next === undefined ? null : next; // Reference to the successor node
this.prev = prev === undefined ? null : prev; // Reference to the predecessor node
this.next = next === undefined ? null : next; // Reference to the successor
this.prev = prev === undefined ? null : prev; // Reference to the predecessor
}
}
```
@@ -598,8 +598,8 @@ As shown in the figure below, there are three common types of linked lists:
/* Doubly linked list node class */
class ListNode {
int val; // Node value
ListNode? next; // Reference to the successor node
ListNode? prev; // Reference to the predecessor node
ListNode? next; // Reference to the successor
ListNode? prev; // Reference to the predecessor
ListNode(this.val, [this.next, this.prev]); // Constructor
}
```
@@ -614,8 +614,8 @@ As shown in the figure below, there are three common types of linked lists:
#[derive(Debug)]
struct ListNode {
val: i32, // Node value
next: Option<Rc<RefCell<ListNode>>>, // Pointer to the successor node
prev: Option<Rc<RefCell<ListNode>>>, // Pointer to the predecessor node
next: Option<Rc<RefCell<ListNode>>>, // Pointer to the successor
prev: Option<Rc<RefCell<ListNode>>>, // Pointer to the predecessor
}
/* Constructor */
@@ -636,8 +636,8 @@ As shown in the figure below, there are three common types of linked lists:
/* Doubly linked list node structure */
typedef struct ListNode {
int val; // Node value
struct ListNode *next; // Pointer to the successor node
struct ListNode *prev; // Pointer to the predecessor node
struct ListNode *next; // Pointer to the successor
struct ListNode *prev; // Pointer to the predecessor
} ListNode;
/* Constructor */
@@ -658,8 +658,8 @@ As shown in the figure below, there are three common types of linked lists:
// Constructor
class ListNode(x: Int) {
val _val: Int = x // Node value
var next: ListNode? = null // Reference to the successor node
var prev: ListNode? = null // Reference to the predecessor node
var next: ListNode? = null // Reference to the successor
var prev: ListNode? = null // Reference to the predecessor
}
```
@@ -669,8 +669,8 @@ As shown in the figure below, there are three common types of linked lists:
# Doubly linked list node class
class ListNode
attr_accessor :val # Node value
attr_accessor :next # Reference to the successor node
attr_accessor :prev # Reference to the predecessor node
attr_accessor :next # Reference to the successor
attr_accessor :prev # Reference to the predecessor
def initialize(val=0, next_node=nil, prev_node=nil)
@val = val
@@ -682,21 +682,21 @@ As shown in the figure below, there are three common types of linked lists:
![Common types of linked lists](linked_list.assets/linkedlist_common_types.png)
## Typical Applications of Linked Lists
## Typical applications of linked lists
Singly linked lists are commonly used to implement stacks, queues, hash tables, and graphs.
Singly linked lists commonly implement stacks, queues, hash tables, and graphs.
- **Stacks and queues**: When insertion and deletion operations both occur at one end of the linked list, it exhibits last-in-first-out characteristics, corresponding to a stack. When insertion operations occur at one end of the linked list and deletion operations occur at the other end, it exhibits first-in-first-out characteristics, corresponding to a queue.
- **Hash tables**: Separate chaining is one of the mainstream solutions for resolving hash collisions. In this approach, all colliding elements are placed in a linked list.
- **Graphs**: An adjacency list is a common way to represent a graph, where each vertex in the graph is associated with a linked list, and each element in the linked list represents another vertex connected to that vertex.
- **Stacks and queues**: Inserting and removing at the same end gives last-in, first-out behavior, forming a stack. Inserting at one end and removing at the other gives first-in, first-out behavior, forming a queue.
- **Hash tables**: Separate chaining is a common collision-handling strategy that places colliding elements in a linked list.
- **Graphs**: An adjacency list associates each vertex with a linked list whose elements represent the other vertices connected to it.
Doubly linked lists are commonly used in scenarios where quick access to the previous and next elements is needed.
Doubly linked lists are useful when both the previous and next elements must be found quickly.
- **Advanced data structures**: For example, in red-black trees and B-trees, we need to access the parent node of a node, which can be achieved by saving a reference to the parent node in the node, similar to a doubly linked list.
- **Browser history**: In web browsers, when a user clicks the forward or backward button, the browser needs to know the previous and next web pages the user visited. The characteristics of doubly linked lists make this operation simple.
- **LRU algorithm**: In cache eviction (LRU) algorithms, we need to quickly find the least recently used data and support quick addition and deletion of nodes. Using a doubly linked list is very suitable for this.
- **Advanced data structures**: In structures such as red-black trees and B-trees, a node may need access to its parent. Storing a parent reference is similar to the backward link in a doubly linked list.
- **Browser history**: The forward and back buttons require access to the next and previous visited pages. A doubly linked list makes this straightforward.
- **LRU caching**: Least recently used eviction needs fast access to the least recently used data and efficient insertion and removal, making doubly linked lists a good fit.
Circular linked lists are commonly used in scenarios that require periodic operations, such as operating system resource scheduling.
Circular linked lists suit cyclic operations, such as operating-system resource scheduling.
- **Round-robin scheduling algorithm**: In operating systems, round-robin scheduling is a common CPU scheduling algorithm that needs to cycle through a set of processes. Each process is assigned a time slice, and when the time slice expires, the CPU switches to the next process. This cyclic operation can be implemented using a circular linked list.
- **Data buffers**: In some data buffer implementations, circular linked lists may also be used. For example, in audio and video players, the data stream may be divided into multiple buffer blocks and placed in a circular linked list to achieve seamless playback.
- **Round-robin scheduling**: This common CPU scheduling algorithm cycles through processes, giving each a time slice before moving to the next. A circular linked list can implement this cycle.
- **Data buffers**: Some buffers use circular linked lists. Audio and video players, for example, may divide a stream into buffer blocks arranged in a circular list for seamless playback.

View File

@@ -1,26 +1,26 @@
# List
# Lists
A <u>list</u> is an abstract data structure concept that represents an ordered collection of elements, supporting operations such as element access, modification, insertion, deletion, and traversal, without requiring users to consider capacity limitations. Lists can be implemented based on linked lists or arrays.
A <u>list</u> is an abstract data structure representing an ordered collection. It supports access, modification, insertion, removal, and traversal without requiring users to manage capacity limits. Lists can be implemented with linked lists or arrays.
- A linked list can naturally be viewed as a list: it supports insertion, deletion, search, and update, and can grow flexibly as needed.
- An array also supports insertion, deletion, search, and update, but because its length is fixed, it can only be regarded as a list with a capacity limit.
- A linked list naturally serves as a list, supporting these operations and flexible dynamic growth.
- An array also supports these operations, but its fixed length makes it a list with a length limit.
When a list is implemented with an array, **its fixed length makes it less practical**. This is because we usually cannot determine in advance how much data we need to store, making it difficult to choose an appropriate capacity. If the capacity is too small, it may fail to meet our needs; if it is too large, memory space will be wasted.
When an array implements a list, **its fixed length limits the list's usefulness**. We often cannot predict how much data we will store. Too small an allocation may not meet our needs; too large an allocation wastes memory.
To solve this problem, we can use a <u>dynamic array</u> to implement a list. It inherits all the advantages of arrays while supporting dynamic resizing during program execution.
A <u>dynamic array</u> solves this problem. It retains the advantages of an array while allowing capacity to grow during execution.
In fact, **the list types provided by the standard libraries of many programming languages are implemented with dynamic arrays**, such as `list` in Python, `ArrayList` in Java, `vector` in C++, and `List` in C#. In the following discussion, we will treat "list" and "dynamic array" as equivalent concepts.
**Many standard-library lists use dynamic arrays**, including Python's `list`, Java's `ArrayList`, C++'s `vector`, and C#'s `List`. In the discussion that follows, we treat lists and dynamic arrays as equivalent concepts.
## Common List Operations
## Common list operations
### Initialize a List
### Initializing a list
We typically initialize a list in one of two ways: empty or with predefined values:
We usually initialize a list either without elements or with explicit initial values:
=== "Python"
```python title="list.py"
# Initialize a list
# Initialize lists
# Without initial values
nums1: list[int] = []
# With initial values
@@ -30,8 +30,8 @@ We typically initialize a list in one of two ways: empty or with predefined valu
=== "C++"
```cpp title="list.cpp"
/* Initialize a list */
// Note that vector in C++ is equivalent to nums as described in this article
/* Initialize lists */
// In C++, vector is the list type used for nums here
// Without initial values
vector<int> nums1;
// With initial values
@@ -41,10 +41,10 @@ We typically initialize a list in one of two ways: empty or with predefined valu
=== "Java"
```java title="list.java"
/* Initialize a list */
/* Initialize lists */
// Without initial values
List<Integer> nums1 = new ArrayList<>();
// With initial values (note that array elements should use the wrapper class Integer[] instead of int[])
// With initial values (use Integer[], the boxed counterpart of int[])
Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 };
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
```
@@ -52,7 +52,7 @@ We typically initialize a list in one of two ways: empty or with predefined valu
=== "C#"
```csharp title="list.cs"
/* Initialize a list */
/* Initialize lists */
// Without initial values
List<int> nums1 = [];
// With initial values
@@ -63,7 +63,7 @@ We typically initialize a list in one of two ways: empty or with predefined valu
=== "Go"
```go title="list_test.go"
/* Initialize a list */
/* Initialize lists */
// Without initial values
nums1 := []int{}
// With initial values
@@ -73,7 +73,7 @@ We typically initialize a list in one of two ways: empty or with predefined valu
=== "Swift"
```swift title="list.swift"
/* Initialize a list */
/* Initialize lists */
// Without initial values
let nums1: [Int] = []
// With initial values
@@ -83,7 +83,7 @@ We typically initialize a list in one of two ways: empty or with predefined valu
=== "JS"
```javascript title="list.js"
/* Initialize a list */
/* Initialize lists */
// Without initial values
const nums1 = [];
// With initial values
@@ -93,7 +93,7 @@ We typically initialize a list in one of two ways: empty or with predefined valu
=== "TS"
```typescript title="list.ts"
/* Initialize a list */
/* Initialize lists */
// Without initial values
const nums1: number[] = [];
// With initial values
@@ -103,7 +103,7 @@ We typically initialize a list in one of two ways: empty or with predefined valu
=== "Dart"
```dart title="list.dart"
/* Initialize a list */
/* Initialize lists */
// Without initial values
List<int> nums1 = [];
// With initial values
@@ -113,7 +113,7 @@ We typically initialize a list in one of two ways: empty or with predefined valu
=== "Rust"
```rust title="list.rs"
/* Initialize a list */
/* Initialize lists */
// Without initial values
let nums1: Vec<i32> = Vec::new();
// With initial values
@@ -123,13 +123,13 @@ We typically initialize a list in one of two ways: empty or with predefined valu
=== "C"
```c title="list.c"
// C does not provide built-in dynamic arrays
// C does not provide a built-in dynamic array
```
=== "Kotlin"
```kotlin title="list.kt"
/* Initialize a list */
/* Initialize lists */
// Without initial values
var nums1 = listOf<Int>()
// With initial values
@@ -140,151 +140,151 @@ We typically initialize a list in one of two ways: empty or with predefined valu
=== "Ruby"
```ruby title="list.rb"
# Initialize a list
# Initialize lists
# Without initial values
nums1 = []
# With initial values
nums = [1, 3, 2, 5, 4]
```
??? 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%E5%88%97%E8%A1%A8%0A%20%20%20%20%23%20%E6%97%A0%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D&cumulative=false&curInstr=4&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%20lists%0A%20%20%20%20%23%20Without%20initial%20values%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20With%20initial%20values%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
### Access Elements
### Accessing an element
Since a list is essentially an array, we can access and update elements in $O(1)$ time complexity, which is very efficient.
Since the list is based on an array, accessing and updating an element are efficient $O(1)$ operations.
=== "Python"
```python title="list.py"
# Access an element
num: int = nums[1] # Access element at index 1
num: int = nums[1] # Access the element at index 1
# Update an element
nums[1] = 0 # Update element at index 1 to 0
nums[1] = 0 # Set the element at index 1 to 0
```
=== "C++"
```cpp title="list.cpp"
/* Access an element */
int num = nums[1]; // Access element at index 1
int num = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Update element at index 1 to 0
nums[1] = 0; // Set the element at index 1 to 0
```
=== "Java"
```java title="list.java"
/* Access an element */
int num = nums.get(1); // Access element at index 1
int num = nums.get(1); // Access the element at index 1
/* Update an element */
nums.set(1, 0); // Update element at index 1 to 0
nums.set(1, 0); // Set the element at index 1 to 0
```
=== "C#"
```csharp title="list.cs"
/* Access an element */
int num = nums[1]; // Access element at index 1
int num = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Update element at index 1 to 0
nums[1] = 0; // Set the element at index 1 to 0
```
=== "Go"
```go title="list_test.go"
/* Access an element */
num := nums[1] // Access element at index 1
num := nums[1] // Access the element at index 1
/* Update an element */
nums[1] = 0 // Update element at index 1 to 0
nums[1] = 0 // Set the element at index 1 to 0
```
=== "Swift"
```swift title="list.swift"
/* Access an element */
let num = nums[1] // Access element at index 1
let num = nums[1] // Access the element at index 1
/* Update an element */
nums[1] = 0 // Update element at index 1 to 0
nums[1] = 0 // Set the element at index 1 to 0
```
=== "JS"
```javascript title="list.js"
/* Access an element */
const num = nums[1]; // Access element at index 1
const num = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Update element at index 1 to 0
nums[1] = 0; // Set the element at index 1 to 0
```
=== "TS"
```typescript title="list.ts"
/* Access an element */
const num: number = nums[1]; // Access element at index 1
const num: number = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Update element at index 1 to 0
nums[1] = 0; // Set the element at index 1 to 0
```
=== "Dart"
```dart title="list.dart"
/* Access an element */
int num = nums[1]; // Access element at index 1
int num = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Update element at index 1 to 0
nums[1] = 0; // Set the element at index 1 to 0
```
=== "Rust"
```rust title="list.rs"
/* Access an element */
let num: i32 = nums[1]; // Access element at index 1
let num: i32 = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Update element at index 1 to 0
nums[1] = 0; // Set the element at index 1 to 0
```
=== "C"
```c title="list.c"
// C does not provide built-in dynamic arrays
// C does not provide a built-in dynamic array
```
=== "Kotlin"
```kotlin title="list.kt"
/* Access an element */
val num = nums[1] // Access element at index 1
val num = nums[1] // Access the element at index 1
/* Update an element */
nums[1] = 0 // Update element at index 1 to 0
nums[1] = 0 // Set the element at index 1 to 0
```
=== "Ruby"
```ruby title="list.rb"
# Access an element
num = nums[1] # Access element at index 1
num = nums[1] # Access the element at index 1
# Update an element
nums[1] = 0 # Update element at index 1 to 0
nums[1] = 0 # Set the element at index 1 to 0
```
??? 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%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E5%85%83%E7%B4%A0%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%E8%AE%BF%E9%97%AE%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%0A%0A%20%20%20%20%23%20%E6%9B%B4%E6%96%B0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E5%B0%86%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%E6%9B%B4%E6%96%B0%E4%B8%BA%200&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=%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%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20Access%20an%20element%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20Access%20the%20element%20at%20index%201%0A%0A%20%20%20%20%23%20Update%20an%20element%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20Set%20the%20element%20at%20index%201%20to%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
### Insert and Delete Elements
### Inserting and removing elements
Compared to arrays, lists can freely add and delete elements. Adding an element at the end of a list has a time complexity of $O(1)$, but inserting and deleting elements still have the same efficiency as arrays, with a time complexity of $O(n)$.
Unlike a fixed array, a list can freely add and remove elements. Appending takes $O(1)$ time, while insertion and removal retain the array's $O(n)$ time complexity.
=== "Python"
@@ -292,7 +292,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
# Clear the list
nums.clear()
# Add elements at the end
# Append elements
nums.append(1)
nums.append(3)
nums.append(2)
@@ -300,10 +300,10 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums.append(4)
# Insert an element in the middle
nums.insert(3, 6) # Insert number 6 at index 3
nums.insert(3, 6) # Insert 6 at index 3
# Delete an element
nums.pop(3) # Delete element at index 3
# Remove an element
nums.pop(3) # Remove the element at index 3
```
=== "C++"
@@ -312,7 +312,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
/* Clear the list */
nums.clear();
/* Add elements at the end */
/* Append elements */
nums.push_back(1);
nums.push_back(3);
nums.push_back(2);
@@ -320,10 +320,10 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums.push_back(4);
/* Insert an element in the middle */
nums.insert(nums.begin() + 3, 6); // Insert number 6 at index 3
nums.insert(nums.begin() + 3, 6); // Insert 6 at index 3
/* Delete an element */
nums.erase(nums.begin() + 3); // Delete element at index 3
/* Remove an element */
nums.erase(nums.begin() + 3); // Remove the element at index 3
```
=== "Java"
@@ -332,7 +332,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
/* Clear the list */
nums.clear();
/* Add elements at the end */
/* Append elements */
nums.add(1);
nums.add(3);
nums.add(2);
@@ -340,10 +340,10 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums.add(4);
/* Insert an element in the middle */
nums.add(3, 6); // Insert number 6 at index 3
nums.add(3, 6); // Insert 6 at index 3
/* Delete an element */
nums.remove(3); // Delete element at index 3
/* Remove an element */
nums.remove(3); // Remove the element at index 3
```
=== "C#"
@@ -352,7 +352,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
/* Clear the list */
nums.Clear();
/* Add elements at the end */
/* Append elements */
nums.Add(1);
nums.Add(3);
nums.Add(2);
@@ -360,10 +360,10 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums.Add(4);
/* Insert an element in the middle */
nums.Insert(3, 6); // Insert number 6 at index 3
nums.Insert(3, 6); // Insert 6 at index 3
/* Delete an element */
nums.RemoveAt(3); // Delete element at index 3
/* Remove an element */
nums.RemoveAt(3); // Remove the element at index 3
```
=== "Go"
@@ -372,7 +372,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
/* Clear the list */
nums = nil
/* Add elements at the end */
/* Append elements */
nums = append(nums, 1)
nums = append(nums, 3)
nums = append(nums, 2)
@@ -380,10 +380,10 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums = append(nums, 4)
/* Insert an element in the middle */
nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert number 6 at index 3
nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert 6 at index 3
/* Delete an element */
nums = append(nums[:3], nums[4:]...) // Delete element at index 3
/* Remove an element */
nums = append(nums[:3], nums[4:]...) // Remove the element at index 3
```
=== "Swift"
@@ -392,7 +392,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
/* Clear the list */
nums.removeAll()
/* Add elements at the end */
/* Append elements */
nums.append(1)
nums.append(3)
nums.append(2)
@@ -400,10 +400,10 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums.append(4)
/* Insert an element in the middle */
nums.insert(6, at: 3) // Insert number 6 at index 3
nums.insert(6, at: 3) // Insert 6 at index 3
/* Delete an element */
nums.remove(at: 3) // Delete element at index 3
/* Remove an element */
nums.remove(at: 3) // Remove the element at index 3
```
=== "JS"
@@ -412,7 +412,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
/* Clear the list */
nums.length = 0;
/* Add elements at the end */
/* Append elements */
nums.push(1);
nums.push(3);
nums.push(2);
@@ -420,10 +420,10 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums.push(4);
/* Insert an element in the middle */
nums.splice(3, 0, 6); // Insert number 6 at index 3
nums.splice(3, 0, 6); // Insert 6 at index 3
/* Delete an element */
nums.splice(3, 1); // Delete element at index 3
/* Remove an element */
nums.splice(3, 1); // Remove the element at index 3
```
=== "TS"
@@ -432,7 +432,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
/* Clear the list */
nums.length = 0;
/* Add elements at the end */
/* Append elements */
nums.push(1);
nums.push(3);
nums.push(2);
@@ -440,10 +440,10 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums.push(4);
/* Insert an element in the middle */
nums.splice(3, 0, 6); // Insert number 6 at index 3
nums.splice(3, 0, 6); // Insert 6 at index 3
/* Delete an element */
nums.splice(3, 1); // Delete element at index 3
/* Remove an element */
nums.splice(3, 1); // Remove the element at index 3
```
=== "Dart"
@@ -452,7 +452,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
/* Clear the list */
nums.clear();
/* Add elements at the end */
/* Append elements */
nums.add(1);
nums.add(3);
nums.add(2);
@@ -460,10 +460,10 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums.add(4);
/* Insert an element in the middle */
nums.insert(3, 6); // Insert number 6 at index 3
nums.insert(3, 6); // Insert 6 at index 3
/* Delete an element */
nums.removeAt(3); // Delete element at index 3
/* Remove an element */
nums.removeAt(3); // Remove the element at index 3
```
=== "Rust"
@@ -472,7 +472,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
/* Clear the list */
nums.clear();
/* Add elements at the end */
/* Append elements */
nums.push(1);
nums.push(3);
nums.push(2);
@@ -480,16 +480,16 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums.push(4);
/* Insert an element in the middle */
nums.insert(3, 6); // Insert number 6 at index 3
nums.insert(3, 6); // Insert 6 at index 3
/* Delete an element */
nums.remove(3); // Delete element at index 3
/* Remove an element */
nums.remove(3); // Remove the element at index 3
```
=== "C"
```c title="list.c"
// C does not provide built-in dynamic arrays
// C does not provide a built-in dynamic array
```
=== "Kotlin"
@@ -498,7 +498,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
/* Clear the list */
nums.clear();
/* Add elements at the end */
/* Append elements */
nums.add(1);
nums.add(3);
nums.add(2);
@@ -506,10 +506,10 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums.add(4);
/* Insert an element in the middle */
nums.add(3, 6); // Insert number 6 at index 3
nums.add(3, 6); // Insert 6 at index 3
/* Delete an element */
nums.remove(3); // Delete element at index 3
/* Remove an element */
nums.remove(3); // Remove the element at index 3
```
=== "Ruby"
@@ -518,7 +518,7 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
# Clear the list
nums.clear
# Add elements at the end
# Append elements
nums << 1
nums << 3
nums << 2
@@ -526,19 +526,19 @@ Compared to arrays, lists can freely add and delete elements. Adding an element
nums << 4
# Insert an element in the middle
nums.insert(3, 6) # Insert number 6 at index 3
nums.insert(3, 6) # Insert 6 at index 3
# Delete an element
nums.delete_at(3) # Delete element at index 3
# Remove an element
nums.delete_at(3) # Remove the element at index 3
```
??? 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%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B8%85%E7%A9%BA%E5%88%97%E8%A1%A8%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%9C%A8%E5%B0%BE%E9%83%A8%E6%B7%BB%E5%8A%A0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%9C%A8%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.insert%283,%206%29%20%20%23%20%E5%9C%A8%E7%B4%A2%E5%BC%95%203%20%E5%A4%84%E6%8F%92%E5%85%A5%E6%95%B0%E5%AD%97%206%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E5%85%83%E7%B4%A0%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E7%B4%A2%E5%BC%95%203%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0&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=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20With%20initial%20values%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Clear%20the%20list%0A%20%20%20%20nums.clear%28%29%0A%20%20%20%20%0A%20%20%20%20%23%20Append%20elements%0A%20%20%20%20nums.append%281%29%0A%20%20%20%20nums.append%283%29%0A%20%20%20%20nums.append%282%29%0A%20%20%20%20nums.append%285%29%0A%20%20%20%20nums.append%284%29%0A%20%20%20%20%0A%20%20%20%20%23%20Insert%20an%20element%20in%20the%20middle%0A%20%20%20%20nums.insert%283%2C%206%29%20%20%23%20Insert%206%20at%20index%203%0A%20%20%20%20%0A%20%20%20%20%23%20Remove%20an%20element%0A%20%20%20%20nums.pop%283%29%20%20%20%20%20%20%20%20%23%20Remove%20the%20element%20at%20index%203&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
### Traverse a List
### Traversing a list
Like arrays, lists can be traversed by index or by directly iterating through elements.
Like an array, a list can be traversed by index or by visiting its elements directly.
=== "Python"
@@ -699,7 +699,7 @@ Like arrays, lists can be traversed by index or by directly iterating through el
=== "C"
```c title="list.c"
// C does not provide built-in dynamic arrays
// C does not provide a built-in dynamic array
```
=== "Kotlin"
@@ -733,20 +733,20 @@ Like arrays, lists can be traversed by index or by directly iterating through el
end
```
??? 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%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%80%9A%E8%BF%87%E7%B4%A2%E5%BC%95%E9%81%8D%E5%8E%86%E5%88%97%E8%A1%A8%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20%E7%9B%B4%E6%8E%A5%E9%81%8D%E5%8E%86%E5%88%97%E8%A1%A8%E5%85%83%E7%B4%A0%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&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=%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%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Traverse%20the%20list%20by%20index%0A%20%20%20%20count%20%3D%200%0A%20%20%20%20for%20i%20in%20range%28len%28nums%29%29%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20nums%5Bi%5D%0A%0A%20%20%20%20%23%20Traverse%20list%20elements%20directly%0A%20%20%20%20for%20num%20in%20nums%3A%0A%20%20%20%20%20%20%20%20count%20%2B%3D%20num&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
### Concatenate Lists
### Concatenating lists
Given a new list `nums1`, we can concatenate it to the end of the original list.
Given another list `nums1`, we can append its elements to the end of the original list.
=== "Python"
```python title="list.py"
# Concatenate two lists
nums1: list[int] = [6, 8, 7, 10, 9]
nums += nums1 # Concatenate list nums1 to the end of nums
nums += nums1 # Append nums1 to nums
```
=== "C++"
@@ -754,7 +754,7 @@ Given a new list `nums1`, we can concatenate it to the end of the original list.
```cpp title="list.cpp"
/* Concatenate two lists */
vector<int> nums1 = { 6, 8, 7, 10, 9 };
// Concatenate list nums1 to the end of nums
// Append nums1 to nums
nums.insert(nums.end(), nums1.begin(), nums1.end());
```
@@ -763,7 +763,7 @@ Given a new list `nums1`, we can concatenate it to the end of the original list.
```java title="list.java"
/* Concatenate two lists */
List<Integer> nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 }));
nums.addAll(nums1); // Concatenate list nums1 to the end of nums
nums.addAll(nums1); // Append nums1 to nums
```
=== "C#"
@@ -771,7 +771,7 @@ Given a new list `nums1`, we can concatenate it to the end of the original list.
```csharp title="list.cs"
/* Concatenate two lists */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.AddRange(nums1); // Concatenate list nums1 to the end of nums
nums.AddRange(nums1); // Append nums1 to nums
```
=== "Go"
@@ -779,7 +779,7 @@ Given a new list `nums1`, we can concatenate it to the end of the original list.
```go title="list_test.go"
/* Concatenate two lists */
nums1 := []int{6, 8, 7, 10, 9}
nums = append(nums, nums1...) // Concatenate list nums1 to the end of nums
nums = append(nums, nums1...) // Append nums1 to nums
```
=== "Swift"
@@ -787,7 +787,7 @@ Given a new list `nums1`, we can concatenate it to the end of the original list.
```swift title="list.swift"
/* Concatenate two lists */
let nums1 = [6, 8, 7, 10, 9]
nums.append(contentsOf: nums1) // Concatenate list nums1 to the end of nums
nums.append(contentsOf: nums1) // Append nums1 to nums
```
=== "JS"
@@ -795,7 +795,7 @@ Given a new list `nums1`, we can concatenate it to the end of the original list.
```javascript title="list.js"
/* Concatenate two lists */
const nums1 = [6, 8, 7, 10, 9];
nums.push(...nums1); // Concatenate list nums1 to the end of nums
nums.push(...nums1); // Append nums1 to nums
```
=== "TS"
@@ -803,7 +803,7 @@ Given a new list `nums1`, we can concatenate it to the end of the original list.
```typescript title="list.ts"
/* Concatenate two lists */
const nums1: number[] = [6, 8, 7, 10, 9];
nums.push(...nums1); // Concatenate list nums1 to the end of nums
nums.push(...nums1); // Append nums1 to nums
```
=== "Dart"
@@ -811,7 +811,7 @@ Given a new list `nums1`, we can concatenate it to the end of the original list.
```dart title="list.dart"
/* Concatenate two lists */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.addAll(nums1); // Concatenate list nums1 to the end of nums
nums.addAll(nums1); // Append nums1 to nums
```
=== "Rust"
@@ -825,7 +825,7 @@ Given a new list `nums1`, we can concatenate it to the end of the original list.
=== "C"
```c title="list.c"
// C does not provide built-in dynamic arrays
// C does not provide a built-in dynamic array
```
=== "Kotlin"
@@ -833,7 +833,7 @@ Given a new list `nums1`, we can concatenate it to the end of the original list.
```kotlin title="list.kt"
/* Concatenate two lists */
val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList()
nums.addAll(nums1) // Concatenate list nums1 to the end of nums
nums.addAll(nums1) // Append nums1 to nums
```
=== "Ruby"
@@ -844,117 +844,117 @@ Given a new list `nums1`, we can concatenate it to the end of the original list.
nums += nums1
```
??? 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%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%8B%BC%E6%8E%A5%E4%B8%A4%E4%B8%AA%E5%88%97%E8%A1%A8%0A%20%20%20%20nums1%20%3D%20%5B6,%208,%207,%2010,%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20%E5%B0%86%E5%88%97%E8%A1%A8%20nums1%20%E6%8B%BC%E6%8E%A5%E5%88%B0%20nums%20%E4%B9%8B%E5%90%8E&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=%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%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Concatenate%20two%20lists%0A%20%20%20%20nums1%20%3D%20%5B6%2C%208%2C%207%2C%2010%2C%209%5D%0A%20%20%20%20nums%20%2B%3D%20nums1%20%20%23%20Append%20nums1%20to%20nums&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
### Sort a List
### Sorting a list
After sorting a list, we can use "binary search" and "two-pointer" algorithms, which are frequently tested in array algorithm problems.
Once the list is sorted, we can apply binary search and two-pointer algorithms, which often appear in array problems.
=== "Python"
```python title="list.py"
# Sort a list
nums.sort() # After sorting, list elements are arranged from smallest to largest
# Sort the list
nums.sort() # After sorting, elements are in ascending order
```
=== "C++"
```cpp title="list.cpp"
/* Sort a list */
sort(nums.begin(), nums.end()); // After sorting, list elements are arranged from smallest to largest
/* Sort the list */
sort(nums.begin(), nums.end()); // After sorting, elements are in ascending order
```
=== "Java"
```java title="list.java"
/* Sort a list */
Collections.sort(nums); // After sorting, list elements are arranged from smallest to largest
/* Sort the list */
Collections.sort(nums); // After sorting, elements are in ascending order
```
=== "C#"
```csharp title="list.cs"
/* Sort a list */
nums.Sort(); // After sorting, list elements are arranged from smallest to largest
/* Sort the list */
nums.Sort(); // After sorting, elements are in ascending order
```
=== "Go"
```go title="list_test.go"
/* Sort a list */
sort.Ints(nums) // After sorting, list elements are arranged from smallest to largest
/* Sort the list */
sort.Ints(nums) // After sorting, elements are in ascending order
```
=== "Swift"
```swift title="list.swift"
/* Sort a list */
nums.sort() // After sorting, list elements are arranged from smallest to largest
/* Sort the list */
nums.sort() // After sorting, elements are in ascending order
```
=== "JS"
```javascript title="list.js"
/* Sort a list */
nums.sort((a, b) => a - b); // After sorting, list elements are arranged from smallest to largest
/* Sort the list */
nums.sort((a, b) => a - b); // After sorting, elements are in ascending order
```
=== "TS"
```typescript title="list.ts"
/* Sort a list */
nums.sort((a, b) => a - b); // After sorting, list elements are arranged from smallest to largest
/* Sort the list */
nums.sort((a, b) => a - b); // After sorting, elements are in ascending order
```
=== "Dart"
```dart title="list.dart"
/* Sort a list */
nums.sort(); // After sorting, list elements are arranged from smallest to largest
/* Sort the list */
nums.sort(); // After sorting, elements are in ascending order
```
=== "Rust"
```rust title="list.rs"
/* Sort a list */
nums.sort(); // After sorting, list elements are arranged from smallest to largest
/* Sort the list */
nums.sort(); // After sorting, elements are in ascending order
```
=== "C"
```c title="list.c"
// C does not provide built-in dynamic arrays
// C does not provide a built-in dynamic array
```
=== "Kotlin"
```kotlin title="list.kt"
/* Sort a list */
nums.sort() // After sorting, list elements are arranged from smallest to largest
/* Sort the list */
nums.sort() // After sorting, elements are in ascending order
```
=== "Ruby"
```ruby title="list.rb"
# Sort a list
nums = nums.sort { |a, b| a <=> b } # After sorting, list elements are arranged from smallest to largest
# Sort the list
nums = nums.sort { |a, b| a <=> b } # After sorting, elements are in ascending order
```
??? 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%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%8E%92%E5%BA%8F%E5%88%97%E8%A1%A8%0A%20%20%20%20nums.sort%28%29%20%20%23%20%E6%8E%92%E5%BA%8F%E5%90%8E%EF%BC%8C%E5%88%97%E8%A1%A8%E5%85%83%E7%B4%A0%E4%BB%8E%E5%B0%8F%E5%88%B0%E5%A4%A7%E6%8E%92%E5%88%97&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=%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%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20%0A%20%20%20%20%23%20Sort%20the%20list%0A%20%20%20%20nums.sort%28%29%20%20%23%20After%20sorting%2C%20elements%20are%20in%20ascending%20order&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
## List Implementation
## Implementing a list
Many programming languages have built-in lists, such as Java, C++, and Python. Their implementations are quite complex, and the parameters are carefully considered, such as initial capacity, expansion multiples, and so on. Interested readers can consult the source code to learn more.
Many languages, including Java, C++, and Python, provide lists. Their implementations are sophisticated, with carefully chosen parameters such as initial capacity and growth factor. Interested readers can study their source code.
To deepen our understanding of how lists work, we attempt to implement a simple list with three key design considerations:
To understand how a list works, let's implement a simplified version with three key design choices.
- **Initial capacity**: Select a reasonable initial capacity for the underlying array. In this example, we choose 10 as the initial capacity.
- **Size tracking**: Declare a variable `size` to record the current number of elements in the list and update it in real-time as elements are inserted and deleted. Based on this variable, we can locate the end of the list and determine whether expansion is needed.
- **Expansion mechanism**: When the list capacity is full upon inserting an element, we need to expand. We create a larger array based on the expansion multiple and then move all elements from the current array to the new array in order. In this example, we specify that the array should be expanded to 2 times its previous size each time.
- **Initial capacity**: Choose a reasonable starting array capacity. We use 10 here.
- **Element count**: Maintain `size`, the number of elements, updating it on insertion and removal. It identifies the list's end and tells us when expansion is needed.
- **Growth mechanism**: If insertion finds the capacity full, allocate a larger array using a growth factor and copy all current elements into it. Here, capacity doubles each time.
```src
[file]{my_list}-[class]{my_list}-[func]{}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.5 KiB

After

Width:  |  Height:  |  Size: 47 KiB

View File

@@ -1,71 +1,71 @@
# Random-Access Memory and Cache *
# Memory and cache *
In the first two sections of this chapter, we explored arrays and linked lists, two fundamental and important data structures that represent two physical layouts: "contiguous storage" and "distributed storage", respectively.
The first two sections of this chapter introduced arrays and linked lists, two fundamental structures representing contiguous and scattered storage, respectively.
In fact, **physical structure largely determines the efficiency with which programs utilize memory and cache**, which in turn affects the overall performance of algorithmic programs.
**Physical structure largely determines how efficiently a program uses memory and cache**, affecting its overall performance.
## Computer Storage Devices
## Computer storage devices
Computers include three types of storage devices: <u>hard disk</u>, <u>random-access memory (RAM)</u>, and <u>cache memory</u>. The following table shows their different roles and performance characteristics in a computer system.
Computers have three types of storage: <u>disk storage</u>, <u>random-access memory (RAM)</u>, and <u>cache memory</u>. The table below compares their roles and performance characteristics.
<p align="center"> Table <id> &nbsp; Computer Storage Devices </p>
<p align="center"> Table <id> &nbsp; Computer storage devices </p>
| | Hard Disk | RAM | Cache |
| -------------- | ------------------------------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------- |
| Purpose | Long-term storage of data, including operating systems, programs, and files | Temporary storage of currently running programs and data being processed | Storage of frequently accessed data and instructions to reduce CPU's accesses to memory |
| Volatility | Data is not lost after power-off | Data is lost after power-off | Data is lost after power-off |
| Capacity | Large, on the order of terabytes (TB) | Small, on the order of gigabytes (GB) | Very small, on the order of megabytes (MB) |
| Speed | Slow, hundreds to thousands of MB/s | Fast, tens of GB/s | Very fast, tens to hundreds of GB/s |
| Cost (CNY/GB) | Inexpensive, from a few tenths of a yuan to a few yuan per GB | Expensive, from tens to hundreds of yuan per GB | Very expensive, effectively bundled with the CPU package |
| | Disk storage | RAM | Cache |
| -------------- | ---------------------------------------- | -------------------------------------- | ------------------------------------------------- |
| Purpose | Long-term storage of the operating system, programs, files, and other data | Temporary storage of running programs and data being processed | Stores frequently accessed data and instructions to reduce CPU accesses to RAM |
| Volatility | Retains data without power | Loses data without power | Loses data without power |
| Capacity | Large, on the TB scale | Smaller, on the GB scale | Very small, on the MB scale |
| Speed | Slower, hundreds to thousands of MB/s | Faster, tens of GB/s | Very fast, tens to hundreds of GB/s |
| Price (Chinese yuan) | Inexpensive, fractions of a yuan to several yuan per GB | More expensive, tens to hundreds of yuan per GB | Very expensive, priced as part of the CPU |
We can imagine the computer storage system as a pyramid, as shown in the diagram below. Storage devices closer to the top are faster, have smaller capacity, and are more expensive. This multi-layered design is deliberate, the result of careful consideration by computer scientists and engineers.
We can picture computer storage as the pyramid in the figure below. Nearer the top, storage is faster, smaller, and more expensive. This hierarchy is a deliberate design by computer scientists and engineers.
- **Hard disk cannot be easily replaced by RAM**. First, data in memory is lost after power-off, making it unsuitable for long-term data storage. Second, memory is tens of times more expensive than hard disk, which makes it difficult to popularize in the consumer market.
- **Cache cannot simultaneously achieve large capacity and high speed**. As the capacity of L1, L2, and L3 caches increases, their physical size becomes larger, and the physical distance between them and the CPU core increases, resulting in longer data transmission time and higher element access latency. With current technology, the multi-layered cache structure represents the best balance point between capacity, speed, and cost.
- **RAM cannot readily replace disk storage**. It loses data when power is removed, making it unsuitable for long-term storage. It also costs tens of times more than disk storage, making such a replacement impractical for consumers.
- **Cache capacity and speed are difficult to maximize together**. From L1 to L2 to L3, increasing capacity means greater physical size and distance from the CPU core, increasing transfer time and access latency. With current technology, a multilevel cache offers the best balance of capacity, speed, and cost.
![Computer Storage System](ram_and_cache.assets/storage_pyramid.png)
![Computer storage hierarchy](ram_and_cache.assets/storage_pyramid.png)
!!! tip
The storage hierarchy of computers embodies a delicate balance among speed, capacity, and cost. In fact, such trade-offs are common across all industrial fields, requiring us to find the optimal balance point between different advantages and constraints.
The storage hierarchy balances speed, capacity, and cost. Such tradeoffs occur throughout industry, requiring us to find the best balance among competing strengths and limitations.
In summary, **hard disks are used for long-term storage of large amounts of data, RAM is used to temporarily store the data being processed during program execution, and cache is used to store frequently accessed data and instructions**, thereby improving program execution efficiency. The three work together to keep the computer system running efficiently.
In general, **disks store large amounts of data long term, RAM temporarily holds data being processed, and caches hold frequently accessed data and instructions** to speed up execution. The three work together to keep the computer efficient.
As shown in the diagram below, during program execution, data is read from the hard disk into RAM for CPU computation. Cache can be viewed as part of the CPU. **By intelligently loading data from RAM**, it provides the CPU with high-speed access to data, significantly improving program execution efficiency and reducing reliance on slower RAM.
As shown in the figure below, a running program reads data from disk into RAM for the CPU to process. The cache can be viewed as part of the CPU: **it intelligently loads data from RAM** and provides faster access, improving execution speed and reducing dependence on slower memory.
![Data Flow Among Hard Disk, RAM, and Cache](ram_and_cache.assets/computer_storage_devices.png)
![Data flow between disk, RAM, and cache](ram_and_cache.assets/computer_storage_devices.png)
## Memory Efficiency of Data Structures
## Memory efficiency of data structures
In terms of memory space utilization, arrays and linked lists each have advantages and limitations.
Arrays and linked lists each have strengths and limitations in memory use.
On one hand, **memory is limited, and the same memory cannot be shared by multiple programs**, so we hope data structures can utilize space as efficiently as possible. Array elements are tightly packed and do not require additional space to store references (pointers) between linked list nodes, thus having higher space efficiency. However, arrays need to allocate sufficient contiguous memory space at once, which may lead to memory waste, and array expansion requires additional time and space costs. In comparison, linked lists perform dynamic memory allocation and deallocation on a "node" basis, providing greater flexibility.
On one hand, **memory is finite, and the same region cannot be shared by multiple programs**, so data structures should use it efficiently. Arrays pack elements tightly without extra references (pointers) between nodes, making them more space-efficient. However, they require a sufficiently large contiguous allocation, which can waste memory, and expansion costs extra time and space. Linked lists instead allocate and reclaim memory node by node, providing greater flexibility.
On the other hand, during program execution, **as memory is repeatedly allocated and freed, the degree of fragmentation of free memory becomes increasingly severe**, leading to reduced memory utilization efficiency. Arrays, due to their contiguous storage approach, are relatively less prone to memory fragmentation. Conversely, linked list elements are distributed in storage, and frequent insertion and deletion operations are more likely to cause memory fragmentation.
On the other hand, **repeated allocation and deallocation increasingly fragment free memory**, reducing its usability. Arrays' contiguous storage is less prone to causing fragmentation. Linked lists store elements in scattered locations, so frequent insertions and deletions are more likely to fragment memory.
## Cache Efficiency of Data Structures
## Cache efficiency of data structures
Although cache has much smaller space capacity than memory, it is much faster than memory and plays a crucial role in program execution speed. Since cache capacity is limited and can only store a small portion of frequently accessed data, when the CPU attempts to access data that is not in the cache, a <u>cache miss</u> occurs, and the CPU must load the required data from the slower memory.
A cache is much smaller than RAM but far faster, making it crucial to execution speed. Its limited capacity holds only a small portion of frequently accessed data. If the CPU requests data not in the cache, a <u>cache miss</u> occurs, and the data must be fetched from slower RAM.
Clearly, **the fewer "cache misses," the higher the efficiency of CPU data reads and writes**, and the better the program performance. We call the proportion of data that the CPU successfully obtains from the cache the <u>cache hit rate</u>, a metric typically used to measure cache efficiency.
Clearly, **fewer cache misses mean more efficient CPU reads and writes** and better program performance. The fraction of accesses successfully served by the cache is the <u>cache hit rate</u>, a common measure of cache efficiency.
To achieve the highest efficiency possible, cache employs the following data loading mechanisms.
Caches use the following mechanisms to improve efficiency.
- **Cache lines**: The cache does not store and load data on a byte-by-byte basis, but rather as cache lines. Compared to byte-by-byte transmission, cache line transmission is more efficient.
- **Prefetching mechanism**: The processor attempts to predict data access patterns (e.g., sequential access, fixed-stride jumping access, etc.) and loads data into the cache according to specific patterns, thereby improving hit rate.
- **Spatial locality**: If a piece of data is accessed, nearby data may also be accessed in the near future. Therefore, when the cache loads a particular piece of data, it also loads nearby data to improve hit rate.
- **Temporal locality**: If a piece of data is accessed, it is likely to be accessed again in the near future. Cache leverages this principle by retaining recently accessed data to improve hit rate.
- **Cache lines**: Data is stored and loaded in cache-line units rather than one byte at a time, making transfers more efficient.
- **Prefetching**: The processor tries to predict access patterns, such as sequential access or fixed strides, and loads matching data into the cache to improve the hit rate.
- **Spatial locality**: Accessing data suggests that nearby data may soon be needed, so the cache loads neighboring data as well.
- **Temporal locality**: Recently accessed data is likely to be accessed again soon, so keeping it in the cache improves the hit rate.
In fact, **arrays and linked lists differ in how efficiently they utilize cache**, mainly in the following respects.
**Arrays and linked lists use the cache differently**, mainly in the following ways.
- **Space occupied**: Linked-list elements occupy more space than array elements, so less useful data can fit in the cache.
- **Cache lines**: Linked list data are scattered throughout memory, while cache loads "by lines," so the proportion of invalid data loaded is higher.
- **Prefetching mechanism**: Arrays have more "predictable" data access patterns than linked lists, making it easier for the system to guess which data will be loaded next.
- **Spatial locality**: Arrays are stored in centralized memory space, so data near loaded data is more likely to be accessed soon.
- **Storage size**: Linked list elements require more space, leaving less room for useful data in the cache.
- **Cache lines**: Linked list data is scattered, so loading a whole cache line brings in a larger proportion of unneeded data.
- **Prefetching**: Array access patterns are more predictable, making it easier to anticipate the next data needed.
- **Spatial locality**: Array elements are stored together, so data near a loaded element is more likely to be accessed soon.
Overall, **arrays have higher cache hit rates, thus they usually outperform linked lists in operation efficiency**. This makes data structures implemented based on arrays more popular when solving algorithmic problems.
Overall, **arrays have higher cache hit rates and usually faster operations than linked lists**. This makes array-based structures popular for algorithmic problems.
It is important to note that **high cache efficiency does not mean arrays are superior to linked lists in all cases**. In practical applications, which data structure to choose should be determined based on specific requirements. For example, both arrays and linked lists can implement the "stack" data structure (which will be discussed in detail in the next chapter), but they are suitable for different scenarios.
However, **better cache efficiency does not make arrays superior in every situation**. Choose a structure based on the requirements. Both arrays and linked lists can implement a stack, discussed in the next chapter, but suit different situations.
- When solving algorithm problems, we tend to prefer stack implementations based on arrays, because they provide higher operation efficiency and the ability of random access, at the cost of needing to pre-allocate a certain amount of memory space for the array.
- If the data volume is very large, the dynamic nature is high, and the expected size of the stack is difficult to estimate, then a stack implementation based on linked lists is more suitable. Linked lists can distribute large amounts of data across different parts of memory and avoid the additional overhead produced by array expansion.
- For algorithm exercises, an array-based stack is often preferable because of faster operations and random access, at the cost of allocating some memory in advance.
- If the dataset is very large, changes frequently, and the stack's size is hard to predict, a linked-list-based stack may be more suitable. It can distribute data throughout memory and avoid the extra cost of array expansion.

View File

@@ -1,86 +1,86 @@
# Summary
### Key Review
### Key takeaways
- Arrays and linked lists are two fundamental data structures, representing two different ways data can be stored in computer memory: contiguous storage and scattered storage. Their strengths and weaknesses complement each other.
- Arrays support random access and use less memory; however, inserting and deleting elements is inefficient, and the length is immutable after initialization.
- Linked lists achieve efficient insertion and deletion of nodes by modifying references (pointers), and can flexibly adjust length; however, node access is inefficient and memory consumption is higher. Common linked list types include singly linked lists, circular linked lists, and doubly linked lists.
- A list is an ordered collection of elements that supports insertion, deletion, search, and modification, typically implemented based on dynamic arrays. It retains the advantages of arrays while allowing flexible adjustment of length.
- The emergence of lists has greatly improved the practicality of arrays, but it may also waste some memory space.
- During program execution, data is primarily stored in memory. Arrays provide higher memory space efficiency, while linked lists offer greater flexibility in memory usage.
- Caches provide fast data access to the CPU through mechanisms such as cache lines, prefetching, and spatial and temporal locality, significantly improving program execution efficiency.
- Because arrays have higher cache hit rates, they are generally more efficient than linked lists. When choosing a data structure, appropriate selection should be made based on specific requirements and scenarios.
- Arrays and linked lists are fundamental structures representing contiguous and scattered memory storage. Their strengths are complementary.
- Arrays support random access and use less memory, but insertion and deletion are slow, and their length is fixed after initialization.
- Linked lists efficiently insert and remove nodes by changing references (pointers), and their length is flexible. However, accessing nodes is slow and they use more memory. Common forms include singly linked, circular, and doubly linked lists.
- A list is an ordered collection supporting insertion, removal, access, and modification. It is usually implemented as a dynamic array, retaining array advantages while allowing its length to change.
- Lists make arrays much more practical, though they may waste some memory.
- During execution, data is mainly stored in RAM. Arrays use memory more efficiently, while linked lists offer more flexible allocation.
- Cache lines, prefetching, spatial locality, and temporal locality provide fast CPU access to data, substantially improving execution speed.
- Arrays usually outperform linked lists because of higher cache hit rates. Choose a structure according to the actual requirements and setting.
### Q & A
**Q**: Does storing an array on the stack versus on the heap affect time efficiency and space efficiency?
**Q**: Does storing an array on the stack or heap affect time and space efficiency?
Arrays stored on the stack and on the heap are both stored in contiguous memory space, so data operation efficiency is basically the same. However, the stack and heap have their own characteristics, leading to the following differences.
Both use contiguous memory, so data operations have essentially the same efficiency. However, the stack and heap differ in these ways.
1. Allocation and deallocation efficiency: The stack is a relatively small piece of memory, with allocation automatically handled by the compiler; the heap is relatively larger and can be dynamically allocated in code, more prone to fragmentation. Therefore, allocation and deallocation operations on the heap are usually slower than on the stack.
2. Size limitations: Stack memory is relatively small, and the heap size is generally limited by available memory. Therefore, the heap is more suitable for storing large arrays.
3. Flexibility: The size of an array on the stack must be determined at compile time, while the size of an array on the heap can be determined dynamically at runtime.
1. Allocation and deallocation: Stack memory is relatively small and allocated automatically by the compiler. The heap is larger, supports dynamic allocation in code, and is more prone to fragmentation. Heap allocation and deallocation are therefore usually slower.
2. Size limits: Stack space is relatively small, while the heap is generally limited by available memory, making it better suited to large arrays.
3. Flexibility: Stack array sizes must be known at compile time, while heap array sizes can be determined at runtime.
**Q**: Why do arrays require elements of the same type, while linked lists do not emphasize this requirement?
**Q**: Why must array elements have the same type, while this requirement is not emphasized for linked lists?
Linked lists are composed of nodes, with nodes connected through references (pointers), and each node can store different types of data, such as `int`, `double`, `string`, `object`, etc.
Linked lists consist of nodes connected by references (pointers). Different nodes can hold different types, such as `int`, `double`, `string`, and `object`.
In contrast, array elements must be of the same type so that their positions can be determined by calculating offsets. For example, if an array contains both `int` and `long` types, with individual elements occupying 4 bytes and 8 bytes respectively, then the following formula cannot be used to calculate the offset, because the array contains two different "element sizes".
Array elements must have the same type so that their positions can be calculated from offsets. If an array contained both `int` and `long`, occupying 4 and 8 bytes respectively, the following formula would not work because there would be two element sizes.
```shell
# element address = array base address (address of the first element) + element size * element index
# Element address = array address (first element's address) + element size * element index
```
**Q**: After deleting node `P`, do we need to set `P.next` to `None`?
**Q**: After removing node `P`, must we set `P.next` to `None`?
It is not necessary to modify `P.next`. From the perspective of the linked list, traversing from the head node to the tail node will no longer encounter `P`. This means that node `P` has been removed from the linked list, and it doesn't matter where node `P` points to at this time—it won't affect the linked list.
Leaving `P.next` unchanged is acceptable. A traversal from the list's head to its tail no longer encounters `P`, so it has been removed. Whatever `P` points to no longer affects the list.
From an algorithms-and-problem-solving perspective, leaving the pointer connected is fine as long as the program logic is correct. From a standard-library implementation perspective, explicitly disconnecting it is safer and clearer. If it is not disconnected and the deleted node is not reclaimed properly, it may affect the reclamation of successor nodes.
For algorithm exercises, leaving it connected is fine as long as the logic is correct. For a standard library, disconnecting it is safer and clearer: if the removed node is not reclaimed properly, its reference may prevent its successor from being reclaimed.
**Q**: In a linked list, the time complexity of insertion and deletion operations is $O(1)$. However, both insertion and deletion require $O(n)$ time to find the element; why isn't the time complexity $O(n)$?
**Q**: Insertion and deletion in a linked list take $O(1)$ time, but locating the element first takes $O(n)$. Why is the overall complexity not $O(n)$?
If the element is first found and then deleted, the time complexity is indeed $O(n)$. However, the advantage of $O(1)$ insertion and deletion in linked lists can be demonstrated in other applications. For example, a deque is well-suited for linked list implementation, where we maintain pointer variables always pointing to the head and tail nodes, with each insertion and deletion operation being $O(1)$.
Finding an element and then deleting it does take $O(n)$ time. However, $O(1)$ insertion and deletion are useful in other settings. A deque, for example, can use a linked list with pointers maintained at the head and tail, giving $O(1)$ operations.
**Q**: In the diagram "Linked List Definition and Storage Methods", does the light blue pointer node occupy a single memory address, or does it share equally with the node value?
**Q**: In the linked list storage diagram, does the light-blue pointer occupy a separate memory location, or share half the node's space with its value?
This diagram is a qualitative representation; a quantitative representation requires analysis based on the specific situation.
The diagram is qualitative. Exact sizes depend on the circumstances.
- Different types of node values occupy different amounts of space, such as `int`, `long`, `double`, and instance objects, etc.
- The amount of memory space occupied by pointer variables depends on the operating system and compilation environment used, usually 8 bytes or 4 bytes.
- Node values of different types, such as `int`, `long`, `double`, and objects, occupy different amounts of space.
- A pointer's size depends on the operating system and compilation environment, and is usually 8 or 4 bytes.
**Q**: Is appending an element at the end of a list always $O(1)$?
**Q**: Does appending to a list always take $O(1)$ time?
If appending an element exceeds the list length, the list must first be expanded before adding. The system allocates a new block of memory and moves all elements from the original list to it, in which case the time complexity becomes $O(n)$.
If appending exceeds the available capacity, the list must first expand. The system allocates new memory and copies all existing elements, making that operation $O(n)$.
**Q**: "The emergence of lists has greatly improved the practicality of arrays, but may result in some wasted memory space"—does this space waste refer to the memory occupied by additional variables such as capacity, length, and expansion factor?
**Q**: When lists waste memory, does this mean the extra variables for capacity, length, and growth factor?
This space waste mainly has two aspects: on one hand, lists typically set an initial length, which we may not need to fully utilize; on the other hand, to prevent frequent expansion, expansion generally multiplies by a coefficient, such as $\times 1.5$. As a result, there will be many empty positions that we typically cannot completely fill.
The main waste has two sources. First, the initial allocation may exceed what we need. Second, to avoid frequent resizing, capacity usually grows by a factor such as $\times 1.5$, leaving empty slots that may never all be filled.
**Q**: In Python, after initializing `n = [1, 2, 3]`, the addresses of these 3 elements are contiguous, but initializing `m = [2, 1, 3]` reveals that each element's id is not continuous; rather, they are the same as those in `n`. Since the addresses of these elements are not contiguous, is `m` still an array?
**Q**: In Python, after `n = [1, 2, 3]`, the three elements seem to have consecutive addresses. But in `m = [2, 1, 3]`, their IDs are not consecutive and match those in `n`. Is `m` still an array?
If we replace list elements with linked list nodes `n = [n1, n2, n3, n4, n5]`, usually these 5 node objects are also scattered throughout memory. However, given a list index, we can still obtain the node memory address in $O(1)$ time, thereby accessing the corresponding node. This is because the array stores references to nodes, not the nodes themselves.
Consider storing linked list nodes instead: `n = [n1, n2, n3, n4, n5]`. These five objects are usually scattered in memory, yet an index still gives a node's address in $O(1)$ time. The array stores references to the nodes, not the nodes themselves.
Unlike many languages, numbers in Python are wrapped as objects, and lists store not the numbers themselves, but references to the numbers. Therefore, we find that the same numbers in two arrays have the same id, and the memory addresses of these numbers need not be contiguous.
Unlike many languages, Python also wraps numbers in objects. A list stores references to those objects rather than the numbers themselves. Thus, the same numbers in the two arrays can have the same IDs, and their addresses need not be contiguous.
**Q**: C++ STL has `std::list` which has already implemented a doubly linked list, but it seems that some algorithm books don't use it directly. Is there a limitation?
**Q**: C++ STL's `std::list` already implements a doubly linked list. Why do algorithm books rarely use it directly? Does it have limitations?
On one hand, we often prefer to use arrays for implementing algorithms and only use linked lists when necessary, mainly for two reasons.
First, we often favor arrays and use linked lists only when needed, mainly for two reasons.
- Space overhead: Since each element requires two additional pointers (one for the previous element and one for the next element), `std::list` typically consumes more space than `std::vector`.
- Cache unfriendliness: Since data is not stored contiguously, `std::list` has lower cache utilization. In general, `std::vector` has better performance.
- Space overhead: Each element needs two extra pointers, to its predecessor and successor, so `std::list` usually consumes more space than `std::vector`.
- Poor cache locality: Its data is not contiguous, making cache use less efficient. In general, `std::vector` performs better.
On the other hand, cases where linked lists are necessary mainly involve binary trees and graphs. Stacks and queues usually use the `stack` and `queue` provided by the programming language, rather than linked lists.
Second, linked structures are mainly needed for binary trees and graphs. For stacks and queues, we usually use the language's provided `stack` and `queue` rather than a linked list directly.
**Q**: Does the operation `res = [[0]] * n` create a 2D list where each `[0]` is independent?
**Q**: Does `res = [[0]] * n` create a two-dimensional list with independent `[0]` entries?
No, they are not independent. In this 2D list, all the `[0]` are actually references to the same object. If we modify one element, we will find that all corresponding elements change accordingly.
No. Every `[0]` is a reference to the same object. Modifying an element through one reference changes the corresponding element seen through all the others.
If we want each `[0]` in the 2D list to be independent, we can use `res = [[0] for _ in range(n)]` to achieve this. The principle of this approach is to initialize $n$ independent `[0]` list objects.
To create independent `[0]` lists, use `res = [[0] for _ in range(n)]`. This initializes $n$ separate list objects.
**Q**: Does the operation `res = [0] * n` create a list where each integer 0 is independent?
**Q**: Does `res = [0] * n` create independent integer zeros?
In this list, all the integer zeros reference the same object. This is because Python uses a caching mechanism for small integers (typically -5 to 256) to maximize object reuse and improve performance.
All zeros in the list refer to the same object. Python caches small integers, usually -5 through 256, to maximize reuse and improve performance.
Although they all reference the same object, we can still modify each element in the list independently. This is because Python integers are "immutable objects". When we modify an element, we actually switch that element to reference a different object, rather than changing the original object itself.
Even so, each list entry can be changed independently because Python integers are immutable. Assigning a new value switches the entry to a different object reference instead of modifying the original object.
However, when list elements are "mutable objects" (such as lists, dictionaries, or class instances), modifying an element directly changes the object itself, and all elements referencing that object will have the same change.
When an element is mutable, such as a list, dictionary, or class instance, modifying the object itself is visible through every reference to it.