Skip to content

LinkedList ​

LinkedList<T> implements a singly linked list with O(1) insertion and removal at the front.

Construction ​

SyntaxDescription
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 ​

MethodSignatureReturnsDescription
pushFront(T) => voidvoidAdd an element to the front
pushBack(T) => voidvoidAdd 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() => usizeusizeNumber of elements
isEmpty() => booleanbooleanWhether the list has no elements
clear() => voidvoidRemove all elements

popFront, popBack, front, and back return T?, call with a presence check or default value.

Complexity ​

OperationTime Complexity
pushFrontO(1)
pushBackO(n)
popFrontO(1)
popBackO(n)
frontO(1)
backO(n)
lenO(1)
isEmptyO(1)
clearO(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());  // 3

front 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());  // 1

popBack ​

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());  // 2

len ​

tyrus
const ll = LinkedList<i32>();

print(ll.len());  // 0

ll.pushBack(1);
ll.pushFront(2);

print(ll.len());  // 2

isEmpty ​

tyrus
const ll = LinkedList<i32>();

print(ll.isEmpty());  // true

ll.pushBack(1);

print(ll.isEmpty());  // false

clear ​

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());      // 0

fromArray ​

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
}