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, insertion, deletion, and traversal, without requiring users to consider capacity limitations. Lists can be implemented based on linked lists or arrays.
- A linked list can naturally be viewed as a list, supporting element insertion, deletion, search, and modification operations, and can flexibly expand dynamically.
- An array also supports element insertion, deletion, search, and modification, but since its length is immutable, it can only be viewed as a list with length limitations.
When implementing lists using arrays, the immutable length property reduces the practicality of the list. This is because we usually cannot determine in advance how much data we need to store, making it difficult to choose an appropriate list length. If the length is too small, it may fail to meet usage requirements; if the length is too large, it will waste memory space.
To solve this problem, we can use a dynamic array to implement a list. It inherits all the advantages of arrays and can dynamically expand during program execution.
In fact, the lists provided in the standard libraries of many programming languages are implemented based on 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.
4.3.1 Common List Operations¶
1. Initialize a List¶
We typically use two initialization methods: "without initial values" and "with initial values":
/* Initialize a list */
// Without initial values
List<Integer> nums1 = new ArrayList<>();
// With initial values (note that array elements should use the wrapper class Integer[] instead of int[])
Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 };
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
Code Visualization
2. Access Elements¶
Since a list is essentially an array, we can access and update elements in \(O(1)\) time complexity, which is very efficient.
Code Visualization
3. Insert and Delete 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)\).
/* Clear the list */
nums.clear();
/* Add 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 an element in the middle */
nums.insert(nums.begin() + 3, 6); // Insert number 6 at index 3
/* Delete an element */
nums.erase(nums.begin() + 3); // Delete element at index 3
/* Clear the list */
nums = nil
/* Add 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 an element in the middle */
nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert number 6 at index 3
/* Delete an element */
nums = append(nums[:3], nums[4:]...) // Delete element at index 3
/* Clear the list */
nums.removeAll()
/* Add elements at the end */
nums.append(1)
nums.append(3)
nums.append(2)
nums.append(5)
nums.append(4)
/* Insert an element in the middle */
nums.insert(6, at: 3) // Insert number 6 at index 3
/* Delete an element */
nums.remove(at: 3) // Delete element at index 3
/* Clear the list */
nums.length = 0;
/* Add elements at the end */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
/* Insert an element in the middle */
nums.splice(3, 0, 6); // Insert number 6 at index 3
/* Delete an element */
nums.splice(3, 1); // Delete element at index 3
/* Clear the list */
nums.length = 0;
/* Add elements at the end */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
/* Insert an element in the middle */
nums.splice(3, 0, 6); // Insert number 6 at index 3
/* Delete an element */
nums.splice(3, 1); // Delete element at index 3
Code Visualization
4. Traverse a List¶
Like arrays, lists can be traversed by index or by directly iterating through elements.
Code Visualization
5. Concatenate Lists¶
Given a new list nums1, we can concatenate it to the end of the original list.
Code Visualization
6. Sort a List¶
After sorting a list, we can use "binary search" and "two-pointer" algorithms, which are frequently tested in array algorithm problems.
Code Visualization
4.3.2 List Implementation¶
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.
To deepen our understanding of how lists work, we attempt to implement a simple list with three key design considerations:
- 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
sizeto 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.
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 by which the list capacity is extended each time
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 extension 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 extension mechanism
if self._size == self.capacity():
self.extend_capacity()
# Move all elements at and after index index backward by one position
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 index forward by one position
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 capacity"""
# Create a new array with length _extend_ratio times 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 list with valid length"""
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 by which the list capacity is extended each time
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;
}
/* Update 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];
}
/* Add elements at the end */
void set(int index, int num) {
if (index < 0 || index >= size())
throw out_of_range("Index out of bounds");
arr[index] = num;
}
/* Direct traversal of list elements */
void add(int num) {
// When the number of elements exceeds capacity, trigger the extension mechanism
if (size() == capacity())
extendCapacity();
arr[size()] = num;
// Update the number of elements
arrSize++;
}
/* Sort list */
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 extension mechanism
if (size() == capacity())
extendCapacity();
// Move all elements after index index forward by one position
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];
// Create a new array with length _extend_ratio times the original array, and copy the original array to the new array
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;
}
/* Driver Code */
void extendCapacity() {
// Create a new array with length extendRatio times the original array
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 list to Vector for printing */
vector<int> toVector() {
// Elements enqueue
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 by which the list capacity is extended each time
/* 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;
}
/* Update 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];
}
/* Add elements at the end */
public void set(int index, int num) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index out of bounds");
arr[index] = num;
}
/* Direct traversal of list elements */
public void add(int num) {
// When the number of elements exceeds capacity, trigger the extension mechanism
if (size == capacity())
extendCapacity();
arr[size] = num;
// Update the number of elements
size++;
}
/* Sort list */
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 extension mechanism
if (size == capacity())
extendCapacity();
// Move all elements after index index forward by one position
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 forward by one position
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;
}
/* Driver Code */
public void extendCapacity() {
// Create a new array with length extendRatio times the original array and copy the original array to the new array
arr = Arrays.copyOf(arr, capacity() * extendRatio);
// Add elements at the end
capacity = arr.length;
}
/* Convert list to array */
public int[] toArray() {
int size = size();
// Elements enqueue
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = get(i);
}
return arr;
}
}
/* List class */
class MyList {
private int[] arr; // Array (stores list elements)
private int arrCapacity = 10; // List capacity
private int arrSize = 0; // List length (current number of elements)
private readonly int extendRatio = 2; // Multiple by which the list capacity is extended each time
/* Constructor */
public MyList() {
arr = new int[arrCapacity];
}
/* Get list length (current number of elements) */
public int Size() {
return arrSize;
}
/* Get list capacity */
public int Capacity() {
return arrCapacity;
}
/* Update element */
public int Get(int index) {
// If the index is out of bounds, throw an exception, as below
if (index < 0 || index >= arrSize)
throw new IndexOutOfRangeException("Index out of bounds");
return arr[index];
}
/* Add elements at the end */
public void Set(int index, int num) {
if (index < 0 || index >= arrSize)
throw new IndexOutOfRangeException("Index out of bounds");
arr[index] = num;
}
/* Direct traversal of list elements */
public void Add(int num) {
// When the number of elements exceeds capacity, trigger the extension mechanism
if (arrSize == arrCapacity)
ExtendCapacity();
arr[arrSize] = num;
// Update the number of elements
arrSize++;
}
/* Sort list */
public void Insert(int index, int num) {
if (index < 0 || index >= arrSize)
throw new IndexOutOfRangeException("Index out of bounds");
// When the number of elements exceeds capacity, trigger the extension mechanism
if (arrSize == arrCapacity)
ExtendCapacity();
// Move all elements after index index forward by one position
for (int j = arrSize - 1; j >= index; j--) {
arr[j + 1] = arr[j];
}
arr[index] = num;
// Update the number of elements
arrSize++;
}
/* Remove element */
public int Remove(int index) {
if (index < 0 || index >= arrSize)
throw new IndexOutOfRangeException("Index out of bounds");
int num = arr[index];
// Move all elements after index forward by one position
for (int j = index; j < arrSize - 1; j++) {
arr[j] = arr[j + 1];
}
// Update the number of elements
arrSize--;
// Return the removed element
return num;
}
/* Driver Code */
public void ExtendCapacity() {
// Create new array of length arrCapacity * extendRatio and copy original array to new array
Array.Resize(ref arr, arrCapacity * extendRatio);
// Add elements at the end
arrCapacity = arr.Length;
}
/* Convert list to array */
public int[] ToArray() {
// Elements enqueue
int[] arr = new int[arrSize];
for (int i = 0; i < arrSize; i++) {
arr[i] = Get(i);
}
return arr;
}
}
/* List class */
type myList struct {
arrCapacity int
arr []int
arrSize int
extendRatio int
}
/* Constructor */
func newMyList() *myList {
return &myList{
arrCapacity: 10, // List capacity
arr: make([]int, 10), // Array (stores list elements)
arrSize: 0, // List length (current number of elements)
extendRatio: 2, // Multiple by which the list capacity is extended each time
}
}
/* Get list length (current number of elements) */
func (l *myList) size() int {
return l.arrSize
}
/* Get list capacity */
func (l *myList) capacity() int {
return l.arrCapacity
}
/* Update element */
func (l *myList) get(index int) int {
// If the index is out of bounds, throw an exception, as below
if index < 0 || index >= l.arrSize {
panic("Index out of bounds")
}
return l.arr[index]
}
/* Add elements at the end */
func (l *myList) set(num, index int) {
if index < 0 || index >= l.arrSize {
panic("Index out of bounds")
}
l.arr[index] = num
}
/* Direct traversal of list elements */
func (l *myList) add(num int) {
// When the number of elements exceeds capacity, trigger the extension mechanism
if l.arrSize == l.arrCapacity {
l.extendCapacity()
}
l.arr[l.arrSize] = num
// Update the number of elements
l.arrSize++
}
/* Sort list */
func (l *myList) insert(num, index int) {
if index < 0 || index >= l.arrSize {
panic("Index out of bounds")
}
// When the number of elements exceeds capacity, trigger the extension mechanism
if l.arrSize == l.arrCapacity {
l.extendCapacity()
}
// Move all elements after index index forward by one position
for j := l.arrSize - 1; j >= index; j-- {
l.arr[j+1] = l.arr[j]
}
l.arr[index] = num
// Update the number of elements
l.arrSize++
}
/* Remove element */
func (l *myList) remove(index int) int {
if index < 0 || index >= l.arrSize {
panic("Index out of bounds")
}
num := l.arr[index]
// Create a new array with length _extend_ratio times the original array, and copy the original array to the new array
for j := index; j < l.arrSize-1; j++ {
l.arr[j] = l.arr[j+1]
}
// Update the number of elements
l.arrSize--
// Return the removed element
return num
}
/* Driver Code */
func (l *myList) extendCapacity() {
// Create a new array with length extendRatio times the original array and copy the original array to the new array
l.arr = append(l.arr, make([]int, l.arrCapacity*(l.extendRatio-1))...)
// Add elements at the end
l.arrCapacity = len(l.arr)
}
/* Return list with valid length */
func (l *myList) toArray() []int {
// Elements enqueue
return l.arr[:l.arrSize]
}
/* List class */
class MyList {
private var arr: [Int] // Array (stores list elements)
private var _capacity: Int // List capacity
private var _size: Int // List length (current number of elements)
private let extendRatio: Int // Multiple by which the list capacity is extended each time
/* Constructor */
init() {
_capacity = 10
_size = 0
extendRatio = 2
arr = Array(repeating: 0, count: _capacity)
}
/* Get list length (current number of elements) */
func size() -> Int {
_size
}
/* Get list capacity */
func capacity() -> Int {
_capacity
}
/* Update element */
func get(index: Int) -> Int {
// Throw error if index out of bounds, same below
if index < 0 || index >= size() {
fatalError("Index out of bounds")
}
return arr[index]
}
/* Add elements at the end */
func set(index: Int, num: Int) {
if index < 0 || index >= size() {
fatalError("Index out of bounds")
}
arr[index] = num
}
/* Direct traversal of list elements */
func add(num: Int) {
// When the number of elements exceeds capacity, trigger the extension mechanism
if size() == capacity() {
extendCapacity()
}
arr[size()] = num
// Update the number of elements
_size += 1
}
/* Sort list */
func insert(index: Int, num: Int) {
if index < 0 || index >= size() {
fatalError("Index out of bounds")
}
// When the number of elements exceeds capacity, trigger the extension mechanism
if size() == capacity() {
extendCapacity()
}
// Move all elements after index index forward by one position
for j in (index ..< size()).reversed() {
arr[j + 1] = arr[j]
}
arr[index] = num
// Update the number of elements
_size += 1
}
/* Remove element */
@discardableResult
func remove(index: Int) -> Int {
if index < 0 || index >= size() {
fatalError("Index out of bounds")
}
let num = arr[index]
// Move all elements after index forward by one position
for j in index ..< (size() - 1) {
arr[j] = arr[j + 1]
}
// Update the number of elements
_size -= 1
// Return the removed element
return num
}
/* Driver Code */
func extendCapacity() {
// Create a new array with length extendRatio times the original array and copy the original array to the new array
arr = arr + Array(repeating: 0, count: capacity() * (extendRatio - 1))
// Add elements at the end
_capacity = arr.count
}
/* Convert list to array */
func toArray() -> [Int] {
Array(arr.prefix(size()))
}
}
/* List class */
class MyList {
#arr = new Array(); // Array (stores list elements)
#capacity = 10; // List capacity
#size = 0; // List length (current number of elements)
#extendRatio = 2; // Multiple by which the list capacity is extended each time
/* Constructor */
constructor() {
this.#arr = new Array(this.#capacity);
}
/* Get list length (current number of elements) */
size() {
return this.#size;
}
/* Get list capacity */
capacity() {
return this.#capacity;
}
/* Update element */
get(index) {
// If the index is out of bounds, throw an exception, as below
if (index < 0 || index >= this.#size) throw new Error('Index out of bounds');
return this.#arr[index];
}
/* Add elements at the end */
set(index, num) {
if (index < 0 || index >= this.#size) throw new Error('Index out of bounds');
this.#arr[index] = num;
}
/* Direct traversal of list elements */
add(num) {
// If length equals capacity, need to expand
if (this.#size === this.#capacity) {
this.extendCapacity();
}
// Add new element to end of list
this.#arr[this.#size] = num;
this.#size++;
}
/* Sort list */
insert(index, num) {
if (index < 0 || index >= this.#size) throw new Error('Index out of bounds');
// When the number of elements exceeds capacity, trigger the extension mechanism
if (this.#size === this.#capacity) {
this.extendCapacity();
}
// Move all elements after index index forward by one position
for (let j = this.#size - 1; j >= index; j--) {
this.#arr[j + 1] = this.#arr[j];
}
// Update the number of elements
this.#arr[index] = num;
this.#size++;
}
/* Remove element */
remove(index) {
if (index < 0 || index >= this.#size) throw new Error('Index out of bounds');
let num = this.#arr[index];
// Create a new array with length _extend_ratio times the original array, and copy the original array to the new array
for (let j = index; j < this.#size - 1; j++) {
this.#arr[j] = this.#arr[j + 1];
}
// Update the number of elements
this.#size--;
// Return the removed element
return num;
}
/* Driver Code */
extendCapacity() {
// Create a new array with length extendRatio times the original array and copy the original array to the new array
this.#arr = this.#arr.concat(
new Array(this.capacity() * (this.#extendRatio - 1))
);
// Add elements at the end
this.#capacity = this.#arr.length;
}
/* Convert list to array */
toArray() {
let size = this.size();
// Elements enqueue
const arr = new Array(size);
for (let i = 0; i < size; i++) {
arr[i] = this.get(i);
}
return arr;
}
}
/* List class */
class MyList {
private arr: Array<number>; // Array (stores list elements)
private _capacity: number = 10; // List capacity
private _size: number = 0; // List length (current number of elements)
private extendRatio: number = 2; // Multiple by which the list capacity is extended each time
/* Constructor */
constructor() {
this.arr = new Array(this._capacity);
}
/* Get list length (current number of elements) */
public size(): number {
return this._size;
}
/* Get list capacity */
public capacity(): number {
return this._capacity;
}
/* Update element */
public get(index: number): number {
// If the index is out of bounds, throw an exception, as below
if (index < 0 || index >= this._size) throw new Error('Index out of bounds');
return this.arr[index];
}
/* Add elements at the end */
public set(index: number, num: number): void {
if (index < 0 || index >= this._size) throw new Error('Index out of bounds');
this.arr[index] = num;
}
/* Direct traversal of list elements */
public add(num: number): void {
// If length equals capacity, need to expand
if (this._size === this._capacity) this.extendCapacity();
// Add new element to end of list
this.arr[this._size] = num;
this._size++;
}
/* Sort list */
public insert(index: number, num: number): void {
if (index < 0 || index >= this._size) throw new Error('Index out of bounds');
// When the number of elements exceeds capacity, trigger the extension mechanism
if (this._size === this._capacity) {
this.extendCapacity();
}
// Move all elements after index index forward by one position
for (let j = this._size - 1; j >= index; j--) {
this.arr[j + 1] = this.arr[j];
}
// Update the number of elements
this.arr[index] = num;
this._size++;
}
/* Remove element */
public remove(index: number): number {
if (index < 0 || index >= this._size) throw new Error('Index out of bounds');
let num = this.arr[index];
// Move all elements after index forward by one position
for (let j = index; j < this._size - 1; j++) {
this.arr[j] = this.arr[j + 1];
}
// Update the number of elements
this._size--;
// Return the removed element
return num;
}
/* Driver Code */
public extendCapacity(): void {
// Create new array of length size and copy original array to new array
this.arr = this.arr.concat(
new Array(this.capacity() * (this.extendRatio - 1))
);
// Add elements at the end
this._capacity = this.arr.length;
}
/* Convert list to array */
public toArray(): number[] {
let size = this.size();
// Elements enqueue
const arr = new Array(size);
for (let i = 0; i < size; i++) {
arr[i] = this.get(i);
}
return arr;
}
}
/* List class */
class MyList {
late List<int> _arr; // Array (stores list elements)
int _capacity = 10; // List capacity
int _size = 0; // List length (current number of elements)
int _extendRatio = 2; // Multiple by which the list capacity is extended each time
/* Constructor */
MyList() {
_arr = List.filled(_capacity, 0);
}
/* Get list length (current number of elements) */
int size() => _size;
/* Get list capacity */
int capacity() => _capacity;
/* Update element */
int get(int index) {
if (index >= _size) throw RangeError('Index out of bounds');
return _arr[index];
}
/* Add elements at the end */
void set(int index, int _num) {
if (index >= _size) throw RangeError('Index out of bounds');
_arr[index] = _num;
}
/* Direct traversal of list elements */
void add(int _num) {
// When the number of elements exceeds capacity, trigger the extension mechanism
if (_size == _capacity) extendCapacity();
_arr[_size] = _num;
// Update the number of elements
_size++;
}
/* Sort list */
void insert(int index, int _num) {
if (index >= _size) throw RangeError('Index out of bounds');
// When the number of elements exceeds capacity, trigger the extension mechanism
if (_size == _capacity) extendCapacity();
// Move all elements after index index forward by one position
for (var j = _size - 1; j >= index; j--) {
_arr[j + 1] = _arr[j];
}
_arr[index] = _num;
// Update the number of elements
_size++;
}
/* Remove element */
int remove(int index) {
if (index >= _size) throw RangeError('Index out of bounds');
int _num = _arr[index];
// Move all elements after index forward by one position
for (var j = index; j < _size - 1; j++) {
_arr[j] = _arr[j + 1];
}
// Update the number of elements
_size--;
// Return the removed element
return _num;
}
/* Driver Code */
void extendCapacity() {
// Create new array with length _extendRatio times original array
final _newNums = List.filled(_capacity * _extendRatio, 0);
// Copy original array to new array
List.copyRange(_newNums, 0, _arr);
// Update _arr reference
_arr = _newNums;
// Add elements at the end
_capacity = _arr.length;
}
/* Convert list to array */
List<int> toArray() {
List<int> arr = [];
for (var i = 0; i < _size; i++) {
arr.add(get(i));
}
return arr;
}
}
/* List class */
#[allow(dead_code)]
struct MyList {
arr: Vec<i32>, // Array (stores list elements)
capacity: usize, // List capacity
size: usize, // List length (current number of elements)
extend_ratio: usize, // Multiple by which the list capacity is extended each time
}
#[allow(unused, unused_comparisons)]
impl MyList {
/* Constructor */
pub fn new(capacity: usize) -> Self {
let mut vec = vec![0; capacity];
Self {
arr: vec,
capacity,
size: 0,
extend_ratio: 2,
}
}
/* Get list length (current number of elements) */
pub fn size(&self) -> usize {
return self.size;
}
/* Get list capacity */
pub fn capacity(&self) -> usize {
return self.capacity;
}
/* Update element */
pub fn get(&self, index: usize) -> i32 {
// If the index is out of bounds, throw an exception, as below
if index >= self.size {
panic!("Index out of bounds")
};
return self.arr[index];
}
/* Add elements at the end */
pub fn set(&mut self, index: usize, num: i32) {
if index >= self.size {
panic!("Index out of bounds")
};
self.arr[index] = num;
}
/* Direct traversal of list elements */
pub fn add(&mut self, num: i32) {
// When the number of elements exceeds capacity, trigger the extension mechanism
if self.size == self.capacity() {
self.extend_capacity();
}
self.arr[self.size] = num;
// Update the number of elements
self.size += 1;
}
/* Sort list */
pub fn insert(&mut self, index: usize, num: i32) {
if index >= self.size() {
panic!("Index out of bounds")
};
// When the number of elements exceeds capacity, trigger the extension mechanism
if self.size == self.capacity() {
self.extend_capacity();
}
// Move all elements after index index forward by one position
for j in (index..self.size).rev() {
self.arr[j + 1] = self.arr[j];
}
self.arr[index] = num;
// Update the number of elements
self.size += 1;
}
/* Remove element */
pub fn remove(&mut self, index: usize) -> i32 {
if index >= self.size() {
panic!("Index out of bounds")
};
let num = self.arr[index];
// Create a new array with length _extend_ratio times the original array, and copy the original array to the new array
for j in 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;
}
/* Driver Code */
pub fn extend_capacity(&mut self) {
// Create new array with length extend_ratio times original, copy original array to new array
let new_capacity = self.capacity * self.extend_ratio;
self.arr.resize(new_capacity, 0);
// Add elements at the end
self.capacity = new_capacity;
}
/* Convert list to array */
pub fn to_array(&self) -> Vec<i32> {
// Elements enqueue
let mut arr = Vec::new();
for i in 0..self.size {
arr.push(self.get(i));
}
arr
}
}
/* List class */
typedef struct {
int *arr; // Array (stores list elements)
int capacity; // List capacity
int size; // List size
int extendRatio; // List expansion multiplier
} MyList;
/* Constructor */
MyList *newMyList() {
MyList *nums = malloc(sizeof(MyList));
nums->capacity = 10;
nums->arr = malloc(sizeof(int) * nums->capacity);
nums->size = 0;
nums->extendRatio = 2;
return nums;
}
/* Destructor */
void delMyList(MyList *nums) {
free(nums->arr);
free(nums);
}
/* Get list length */
int size(MyList *nums) {
return nums->size;
}
/* Get list capacity */
int capacity(MyList *nums) {
return nums->capacity;
}
/* Update element */
int get(MyList *nums, int index) {
assert(index >= 0 && index < nums->size);
return nums->arr[index];
}
/* Add elements at the end */
void set(MyList *nums, int index, int num) {
assert(index >= 0 && index < nums->size);
nums->arr[index] = num;
}
/* Direct traversal of list elements */
void add(MyList *nums, int num) {
if (size(nums) == capacity(nums)) {
extendCapacity(nums); // Expand capacity
}
nums->arr[size(nums)] = num;
nums->size++;
}
/* Sort list */
void insert(MyList *nums, int index, int num) {
assert(index >= 0 && index < size(nums));
// When the number of elements exceeds capacity, trigger the extension mechanism
if (size(nums) == capacity(nums)) {
extendCapacity(nums); // Expand capacity
}
for (int i = size(nums); i > index; --i) {
nums->arr[i] = nums->arr[i - 1];
}
nums->arr[index] = num;
nums->size++;
}
/* Remove element */
// Note: stdio.h occupies the remove keyword
int removeItem(MyList *nums, int index) {
assert(index >= 0 && index < size(nums));
int num = nums->arr[index];
for (int i = index; i < size(nums) - 1; i++) {
nums->arr[i] = nums->arr[i + 1];
}
nums->size--;
return num;
}
/* Driver Code */
void extendCapacity(MyList *nums) {
// Allocate space first
int newCapacity = capacity(nums) * nums->extendRatio;
int *extend = (int *)malloc(sizeof(int) * newCapacity);
int *temp = nums->arr;
// Copy old data to new data
for (int i = 0; i < size(nums); i++)
extend[i] = nums->arr[i];
// Free old data
free(temp);
// Update new data
nums->arr = extend;
nums->capacity = newCapacity;
}
/* Convert list to Array for printing */
int *toArray(MyList *nums) {
return nums->arr;
}
/* List class */
class MyList {
private var arr: IntArray = intArrayOf() // Array (stores list elements)
private var capacity: Int = 10 // List capacity
private var size: Int = 0 // List length (current number of elements)
private var extendRatio: Int = 2 // Multiple by which the list capacity is extended each time
/* Constructor */
init {
arr = IntArray(capacity)
}
/* Get list length (current number of elements) */
fun size(): Int {
return size
}
/* Get list capacity */
fun capacity(): Int {
return capacity
}
/* Update element */
fun get(index: Int): Int {
// If the index is out of bounds, throw an exception, as below
if (index < 0 || index >= size)
throw IndexOutOfBoundsException("Index out of bounds")
return arr[index]
}
/* Add elements at the end */
fun set(index: Int, num: Int) {
if (index < 0 || index >= size)
throw IndexOutOfBoundsException("Index out of bounds")
arr[index] = num
}
/* Direct traversal of list elements */
fun add(num: Int) {
// When the number of elements exceeds capacity, trigger the extension mechanism
if (size == capacity())
extendCapacity()
arr[size] = num
// Update the number of elements
size++
}
/* Sort list */
fun insert(index: Int, num: Int) {
if (index < 0 || index >= size)
throw IndexOutOfBoundsException("Index out of bounds")
// When the number of elements exceeds capacity, trigger the extension mechanism
if (size == capacity())
extendCapacity()
// Move all elements after index index forward by one position
for (j in size - 1 downTo index)
arr[j + 1] = arr[j]
arr[index] = num
// Update the number of elements
size++
}
/* Remove element */
fun remove(index: Int): Int {
if (index < 0 || index >= size)
throw IndexOutOfBoundsException("Index out of bounds")
val num = arr[index]
// Move all elements after index forward by one position
for (j in index..<size - 1)
arr[j] = arr[j + 1]
// Update the number of elements
size--
// Return the removed element
return num
}
/* Driver Code */
fun extendCapacity() {
// Create a new array with length extendRatio times the original array and copy the original array to the new array
arr = arr.copyOf(capacity() * extendRatio)
// Add elements at the end
capacity = arr.size
}
/* Convert list to array */
fun toArray(): IntArray {
val size = size()
// Elements enqueue
val arr = IntArray(size)
for (i in 0..<size) {
arr[i] = get(i)
}
return arr
}
}
### List class ###
class MyList
attr_reader :size # Get list length (current number of elements)
attr_reader :capacity # Get list capacity
### Constructor ###
def initialize
@capacity = 10
@size = 0
@extend_ratio = 2
@arr = Array.new(capacity)
end
### Access element ###
def get(index)
# If the index is out of bounds, throw an exception, as below
raise IndexError, "Index out of bounds" if index < 0 || index >= size
@arr[index]
end
### Access element ###
def set(index, num)
raise IndexError, "Index out of bounds" if index < 0 || index >= size
@arr[index] = num
end
### Add element at end ###
def add(num)
# When the number of elements exceeds capacity, trigger the extension mechanism
extend_capacity if size == capacity
@arr[size] = num
# Update the number of elements
@size += 1
end
### Insert element in middle ###
def insert(index, num)
raise IndexError, "Index out of bounds" if index < 0 || index >= size
# When the number of elements exceeds capacity, trigger the extension mechanism
extend_capacity if size == capacity
# Move all elements after index index forward by one position
for j in (size - 1).downto(index)
@arr[j + 1] = @arr[j]
end
@arr[index] = num
# Update the number of elements
@size += 1
end
### Delete element ###
def remove(index)
raise IndexError, "Index out of bounds" if index < 0 || index >= size
num = @arr[index]
# Move all elements after index forward by one position
for j in index...size
@arr[j] = @arr[j + 1]
end
# Update the number of elements
@size -= 1
# Return the removed element
num
end
### Expand list capacity ###
def extend_capacity
# Create new array with length extend_ratio times original, copy original array to new array
arr = @arr.dup + Array.new(capacity * (@extend_ratio - 1))
# Add elements at the end
@capacity = arr.length
end
### Convert list to array ###
def to_array
sz = size
# Elements enqueue
arr = Array.new(sz)
for i in 0...sz
arr[i] = get(i)
end
arr
end
end