4.3 List¶
A list is an abstract data structure concept that represents an ordered collection of elements, supporting operations such as element access, modification, addition, deletion, and traversal, without requiring users to consider capacity limitations. Lists can be implemented based on linked lists or arrays.
- A linked list inherently serves as a list, supporting operations for adding, deleting, searching, and modifying elements, with the flexibility to dynamically adjust its size.
- Arrays also support these operations, but due to their immutable length, they can be considered as a list with a length limit.
When implementing lists using arrays, the immutability of length reduces the practicality of the list. This is because predicting the amount of data to be stored in advance is often challenging, making it difficult to choose an appropriate list length. If the length is too small, it may not meet the requirements; if too large, it may waste memory space.
To solve this problem, we can implement lists using a dynamic array. It inherits the advantages of arrays and can dynamically expand during program execution.
In fact, many programming languages' standard libraries implement lists using dynamic arrays, such as Python's list
, Java's ArrayList
, C++'s vector
, and C#'s List
. In the following discussion, we will consider "list" and "dynamic array" as synonymous concepts.
4.3.1 Common list operations¶
1. Initializing a list¶
We typically use two initialization methods: "without initial values" and "with initial values".
/* Initialize list */
// Without initial values
List<Integer> nums1 = new ArrayList<>();
// With initial values (note the element type should be the wrapper class Integer[] for int[])
Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 };
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
2. Accessing elements¶
Lists are essentially arrays, thus they can access and update elements in \(O(1)\) time, which is very efficient.
3. Inserting and removing elements¶
Compared to arrays, lists offer more flexibility in adding and removing elements. While adding elements to the end of a list is an \(O(1)\) operation, the efficiency of inserting and removing elements elsewhere in the list remains the same as in arrays, with a time complexity of \(O(n)\).
/* Clear list */
nums.clear();
/* Append elements at the end */
nums.push_back(1);
nums.push_back(3);
nums.push_back(2);
nums.push_back(5);
nums.push_back(4);
/* Insert element in the middle */
nums.insert(nums.begin() + 3, 6); // Insert number 6 at index 3
/* Remove elements */
nums.erase(nums.begin() + 3); // Remove the element at index 3
/* Clear list */
nums = nil
/* Append elements at the end */
nums = append(nums, 1)
nums = append(nums, 3)
nums = append(nums, 2)
nums = append(nums, 5)
nums = append(nums, 4)
/* Insert element in the middle */
nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert number 6 at index 3
/* Remove elements */
nums = append(nums[:3], nums[4:]...) // Remove the element at index 3
/* Clear list */
nums.removeAll()
/* Append elements at the end */
nums.append(1)
nums.append(3)
nums.append(2)
nums.append(5)
nums.append(4)
/* Insert element in the middle */
nums.insert(6, at: 3) // Insert number 6 at index 3
/* Remove elements */
nums.remove(at: 3) // Remove the element at index 3
// Clear list
nums.clearRetainingCapacity();
// Append elements at the end
try nums.append(1);
try nums.append(3);
try nums.append(2);
try nums.append(5);
try nums.append(4);
// Insert element in the middle
try nums.insert(3, 6); // Insert number 6 at index 3
// Remove elements
_ = nums.orderedRemove(3); // Remove the element at index 3
4. Iterating the list¶
Similar to arrays, lists can be iterated either by using indices or by directly iterating through each element.
5. Concatenating lists¶
Given a new list nums1
, we can append it to the end of the original list.
6. Sorting the list¶
Once the list is sorted, we can employ algorithms commonly used in array-related algorithm problems, such as "binary search" and "two-pointer" algorithms.
4.3.2 List implementation¶
Many programming languages come with built-in lists, including Java, C++, Python, etc. Their implementations tend to be intricate, featuring carefully considered settings for various parameters, like initial capacity and expansion factors. Readers who are curious can delve into the source code for further learning.
To enhance our understanding of how lists work, we will attempt to implement a simplified version of a list, focusing on three crucial design aspects:
- Initial capacity: Choose a reasonable initial capacity for the array. In this example, we choose 10 as the initial capacity.
- Size recording: Declare a variable
size
to record the current number of elements in the list, updating in real-time with element insertion and deletion. With this variable, we can locate the end of the list and determine whether expansion is needed. - Expansion mechanism: If the list reaches full capacity upon an element insertion, an expansion process is required. This involves creating a larger array based on the expansion factor, and then transferring all elements from the current array to the new one. In this example, we stipulate that the array size should double with each expansion.
class MyList:
"""List class"""
def __init__(self):
"""Constructor"""
self._capacity: int = 10 # List capacity
self._arr: list[int] = [0] * self._capacity # Array (stores list elements)
self._size: int = 0 # List length (current number of elements)
self._extend_ratio: int = 2 # Multiple for each list expansion
def size(self) -> int:
"""Get list length (current number of elements)"""
return self._size
def capacity(self) -> int:
"""Get list capacity"""
return self._capacity
def get(self, index: int) -> int:
"""Access element"""
# If the index is out of bounds, throw an exception, as below
if index < 0 or index >= self._size:
raise IndexError("Index out of bounds")
return self._arr[index]
def set(self, num: int, index: int):
"""Update element"""
if index < 0 or index >= self._size:
raise IndexError("Index out of bounds")
self._arr[index] = num
def add(self, num: int):
"""Add element at the end"""
# When the number of elements exceeds capacity, trigger the expansion mechanism
if self.size() == self.capacity():
self.extend_capacity()
self._arr[self._size] = num
self._size += 1
def insert(self, num: int, index: int):
"""Insert element in the middle"""
if index < 0 or index >= self._size:
raise IndexError("Index out of bounds")
# When the number of elements exceeds capacity, trigger the expansion mechanism
if self._size == self.capacity():
self.extend_capacity()
# Move all elements after `index` one position backward
for j in range(self._size - 1, index - 1, -1):
self._arr[j + 1] = self._arr[j]
self._arr[index] = num
# Update the number of elements
self._size += 1
def remove(self, index: int) -> int:
"""Remove element"""
if index < 0 or index >= self._size:
raise IndexError("Index out of bounds")
num = self._arr[index]
# Move all elements after `index` one position forward
for j in range(index, self._size - 1):
self._arr[j] = self._arr[j + 1]
# Update the number of elements
self._size -= 1
# Return the removed element
return num
def extend_capacity(self):
"""Extend list"""
# Create a new array of _extend_ratio times the length of the original array and copy the original array to the new array
self._arr = self._arr + [0] * self.capacity() * (self._extend_ratio - 1)
# Update list capacity
self._capacity = len(self._arr)
def to_array(self) -> list[int]:
"""Return a list of valid lengths"""
return self._arr[: self._size]
/* List class */
class MyList {
private:
int *arr; // Array (stores list elements)
int arrCapacity = 10; // List capacity
int arrSize = 0; // List length (current number of elements)
int extendRatio = 2; // Multiple for each list expansion
public:
/* Constructor */
MyList() {
arr = new int[arrCapacity];
}
/* Destructor */
~MyList() {
delete[] arr;
}
/* Get list length (current number of elements)*/
int size() {
return arrSize;
}
/* Get list capacity */
int capacity() {
return arrCapacity;
}
/* Access element */
int get(int index) {
// If the index is out of bounds, throw an exception, as below
if (index < 0 || index >= size())
throw out_of_range("Index out of bounds");
return arr[index];
}
/* Update element */
void set(int index, int num) {
if (index < 0 || index >= size())
throw out_of_range("Index out of bounds");
arr[index] = num;
}
/* Add element at the end */
void add(int num) {
// When the number of elements exceeds capacity, trigger the expansion mechanism
if (size() == capacity())
extendCapacity();
arr[size()] = num;
// Update the number of elements
arrSize++;
}
/* Insert element in the middle */
void insert(int index, int num) {
if (index < 0 || index >= size())
throw out_of_range("Index out of bounds");
// When the number of elements exceeds capacity, trigger the expansion mechanism
if (size() == capacity())
extendCapacity();
// Move all elements after `index` one position backward
for (int j = size() - 1; j >= index; j--) {
arr[j + 1] = arr[j];
}
arr[index] = num;
// Update the number of elements
arrSize++;
}
/* Remove element */
int remove(int index) {
if (index < 0 || index >= size())
throw out_of_range("Index out of bounds");
int num = arr[index];
// Move all elements after `index` one position forward
for (int j = index; j < size() - 1; j++) {
arr[j] = arr[j + 1];
}
// Update the number of elements
arrSize--;
// Return the removed element
return num;
}
/* Extend list */
void extendCapacity() {
// Create a new array with a length multiple of the original array by extendRatio
int newCapacity = capacity() * extendRatio;
int *tmp = arr;
arr = new int[newCapacity];
// Copy all elements from the original array to the new array
for (int i = 0; i < size(); i++) {
arr[i] = tmp[i];
}
// Free memory
delete[] tmp;
arrCapacity = newCapacity;
}
/* Convert the list to a Vector for printing */
vector<int> toVector() {
// Only convert elements within valid length range
vector<int> vec(size());
for (int i = 0; i < size(); i++) {
vec[i] = arr[i];
}
return vec;
}
};
/* List class */
class MyList {
private int[] arr; // Array (stores list elements)
private int capacity = 10; // List capacity
private int size = 0; // List length (current number of elements)
private int extendRatio = 2; // Multiple for each list expansion
/* Constructor */
public MyList() {
arr = new int[capacity];
}
/* Get list length (current number of elements) */
public int size() {
return size;
}
/* Get list capacity */
public int capacity() {
return capacity;
}
/* Access element */
public int get(int index) {
// If the index is out of bounds, throw an exception, as below
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index out of bounds");
return arr[index];
}
/* Update element */
public void set(int index, int num) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index out of bounds");
arr[index] = num;
}
/* Add element at the end */
public void add(int num) {
// When the number of elements exceeds capacity, trigger the expansion mechanism
if (size == capacity())
extendCapacity();
arr[size] = num;
// Update the number of elements
size++;
}
/* Insert element in the middle */
public void insert(int index, int num) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index out of bounds");
// When the number of elements exceeds capacity, trigger the expansion mechanism
if (size == capacity())
extendCapacity();
// Move all elements after `index` one position backward
for (int j = size - 1; j >= index; j--) {
arr[j + 1] = arr[j];
}
arr[index] = num;
// Update the number of elements
size++;
}
/* Remove element */
public int remove(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index out of bounds");
int num = arr[index];
// Move all elements after `index` one position forward
for (int j = index; j < size - 1; j++) {
arr[j] = arr[j + 1];
}
// Update the number of elements
size--;
// Return the removed element
return num;
}
/* Extend list */
public void extendCapacity() {
// Create a new array with a length multiple of the original array by extendRatio, and copy the original array to the new array
arr = Arrays.copyOf(arr, capacity() * extendRatio);
// Update list capacity
capacity = arr.length;
}
/* Convert the list to an array */
public int[] toArray() {
int size = size();
// Only convert elements within valid length range
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = get(i);
}
return arr;
}
}