LinkedList
LinkedList<T> implements a singly linked list with O(1) insertion and removal at the front.
Construction
| Syntax | Description |
|---|---|
LinkedList<T>() | Create a new empty linked list |
LinkedList.fromArray(arr) | Create a linked list with the elements of arr in order |
The type parameter T determines the element type. T can be a scalar value type (boolean, char, integer, or float); heap-owned values such as string are not supported.
Methods
| Method | Signature | Returns | Description |
|---|---|---|---|
pushFront | (T) => void | void | Add an element to the front |
pushBack | (T) => void | void | Add an element to the back |
popFront | () => T? | T? | Remove and return the front element, or empty if empty |
popBack | () => T? | T? | Remove and return the back element, or empty if empty |
front | () => T? | T? | Return the front element without removing it, or empty if empty |
back | () => T? | T? | Return the back element without removing it, or empty if empty |
len | () => usize | usize | Number of elements |
isEmpty | () => boolean | boolean | Whether the list has no elements |
clear | () => void | void | Remove all elements |
popFront, popBack, front, and back return T?, call with a presence check or default value.
Complexity
| Operation | Time Complexity |
|---|---|
pushFront | O(1) |
pushBack | O(n) |
popFront | O(1) |
popBack | O(n) |
front | O(1) |
back | O(n) |
len | O(1) |
isEmpty | O(1) |
clear | O(n) |
Examples
Construction
tyrus
import { LinkedList } from "tyrus:algorithm";
const ll = LinkedList<i32>();pushFront and pushBack
tyrus
const ll = LinkedList<i32>();
ll.pushFront(1);
ll.pushBack(2);
ll.pushBack(3);
print(ll.len()); // 3front and back
tyrus
const ll = LinkedList<i32>();
ll.pushBack(10);
ll.pushBack(20);
const f: i32? = ll.front();
if (f) {
print(f); // 10
}
const b: i32? = ll.back();
if (b) {
print(b); // 20
}popFront
tyrus
const ll = LinkedList<i32>();
ll.pushBack(1);
ll.pushBack(2);
ll.pushBack(3);
const p1: i32? = ll.popFront();
if (p1) {
print(p1); // 1
}
const p2: i32? = ll.popFront();
if (p2) {
print(p2); // 2
}
print(ll.len()); // 1popBack
tyrus
const ll = LinkedList<i32>();
ll.pushBack(1);
ll.pushBack(2);
ll.pushBack(3);
const p: i32? = ll.popBack();
if (p) {
print(p); // 3
}
print(ll.len()); // 2len
tyrus
const ll = LinkedList<i32>();
print(ll.len()); // 0
ll.pushBack(1);
ll.pushFront(2);
print(ll.len()); // 2isEmpty
tyrus
const ll = LinkedList<i32>();
print(ll.isEmpty()); // true
ll.pushBack(1);
print(ll.isEmpty()); // falseclear
tyrus
const ll = LinkedList<i32>();
ll.pushBack(1);
ll.pushBack(2);
ll.pushBack(3);
print(ll.len()); // 3
ll.clear();
print(ll.isEmpty()); // true
print(ll.len()); // 0fromArray
tyrus
const vals: i32[] = [7, 8, 9];
const ll = LinkedList.fromArray(vals);
print(ll.len()); // 3
const f: i32? = ll.front();
if (f) {
print(f); // 7
}
const b: i32? = ll.back();
if (b) {
print(b); // 9
}