Grav v1.14.0

LinkedList

import "std/collections" (included in import "std") · namespace std.collections

LinkedList<T> is a doubly linked list: adding and removing at either end is O(1), but reaching element i walks from the nearer end (O(n)). Prefer Array in general; use a linked list when you mostly add and remove at the ends and never index. (A Deque also does both ends in O(1) and indexes in O(1).)

grav
import "std"

fn main() {
    let list = new LinkedList<string>()
    list.addLast("b")
    list.addLast("c")
    list.addFirst("a")
    print(list)
    print("${list.first()} ${list.last()} ${list.get(1)}")
    print(list.removeFirst())
    list.reverse()
    print(list)
}
Output
["a", "b", "c"]
a c b
a
["c", "b"]

Removing from an empty list throws StateError; a bad index throws IndexError.

API

class LinkedNode<T>

Constructors

  • new LinkedNode(value: T)

Fields

  • value: T
  • prev: LinkedNode<T>
  • next: LinkedNode<T>

class LinkedList<T> implements Iterable<T>

Constructors

  • new LinkedList()

Methods

  • fn size() -> int — The number of elements.
  • fn length() -> int — The number of elements (same as size()).
  • fn isEmpty() -> bool — Whether the list is empty.
  • fn clear() — Removes every element.
  • fn addFirst(item: T) — Adds an element at the front (O(1)).
  • fn addLast(item: T) — Adds an element at the back (O(1)).
  • fn add(item: T) — Adds an element at the back (same as addLast).
  • fn removeFirst() -> T — Removes and returns the first element (StateError when empty).
  • fn removeLast() -> T — Removes and returns the last element (StateError when empty).
  • fn first() -> T — The first element (StateError when empty).
  • fn last() -> T — The last element (StateError when empty).
  • fn get(i: int) -> T — The element at index i (walks the list: O(i)).
  • fn set(i: int, item: T) — Replaces the element at index i.
  • fn removeAt(i: int) -> T — Removes and returns the element at index i.
  • fn remove(item: T) -> bool — Removes the first element equal to item; reports whether one was found.
  • fn contains(item: T) -> bool — Whether some element equals item.
  • fn forEach(f: fn(T)) — Calls f on each element, front to back.
  • fn iterator() -> LinkedListIterator<T> — Walks the elements front to back, one node at a time (what for (x in list) uses).
  • fn reverse() — Reverses the order of the elements in place.
  • fn toString() -> string — As text: [1, 2, 3] (strings in quotes).
  • fn toArray() -> Array<T> — The elements as a new Array, front to back.

class LinkedListIterator<T> implements Iterator<T>

Walks a LinkedList from a node to the back.

Constructors

  • new LinkedListIterator(node: LinkedNode<T>)

Methods

  • fn hasNext() -> bool
  • fn next() -> T

Edit this page on GitHub