Skip to content

DoubleLinkedList ​

DoubleLinkedList<T> implements a doubly linked list with O(1) insertion and removal at both ends.

Construction ​

SyntaxDescription
DoubleLinkedList<T>()Create a new empty doubly linked list
DoubleLinkedList.fromArray(arr)Create a doubly 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(1)
popFrontO(1)
popBackO(1)
frontO(1)
backO(1)
lenO(1)
isEmptyO(1)
clearO(n)

Examples ​

Construction ​

tyrus
import { DoubleLinkedList } from "tyrus:algorithm";

const dll = DoubleLinkedList<i32>();

pushFront and pushBack ​

tyrus
const dll = DoubleLinkedList<i32>();

dll.pushFront(1);
dll.pushBack(2);
dll.pushBack(3);

print(dll.len());  // 3

front and back ​

tyrus
const dll = DoubleLinkedList<i32>();

dll.pushBack(10);
dll.pushBack(20);

const f: i32? = dll.front();
if (f) {
    print(f);  // 10
}

const b: i32? = dll.back();
if (b) {
    print(b);  // 20
}

popFront ​

tyrus
const dll = DoubleLinkedList<i32>();

dll.pushBack(1);
dll.pushBack(2);
dll.pushBack(3);

const p1: i32? = dll.popFront();
if (p1) {
    print(p1);  // 1
}

const p2: i32? = dll.popFront();
if (p2) {
    print(p2);  // 2
}

print(dll.len());  // 1

popBack ​

tyrus
const dll = DoubleLinkedList<i32>();

dll.pushBack(1);
dll.pushBack(2);
dll.pushBack(3);

const p: i32? = dll.popBack();
if (p) {
    print(p);  // 3
}

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

len ​

tyrus
const dll = DoubleLinkedList<i32>();

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

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

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

isEmpty ​

tyrus
const dll = DoubleLinkedList<i32>();

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

dll.pushBack(1);

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

clear ​

tyrus
const dll = DoubleLinkedList<i32>();

dll.pushBack(1);
dll.pushBack(2);
dll.pushBack(3);

print(dll.len());  // 3

dll.clear();

print(dll.isEmpty());  // true
print(dll.len());      // 0

fromArray ​

tyrus
const vals: i32[] = [7, 8, 9];
const dll = DoubleLinkedList.fromArray(vals);

print(dll.len());  // 3

const f: i32? = dll.front();
if (f) {
    print(f);  // 7
}

const b: i32? = dll.back();
if (b) {
    print(b);  // 9
}