Programming Search⌘K

Taskcore

Use a linked list

Also called linked list operations, doubly linked list, build a linked list, LinkedList, std::list, container/list, push front and push back, remove a node.

Push and pop at both ends of a linked list and remove a node in the middle, with the standard list type or with nodes that you build, and see why a Rust list is hard to write.

Task

Run a list of operations on a new, empty linked list, and return the items of the list from front to back. The function run_ops(ops) takes 0 to 1000 operations. Each operation is one of these strings:

  • push_front N puts N before the first item.
  • push_back N puts N after the last item.
  • pop_front and pop_back remove the first or the last item. The input does not pop an empty list.
  • remove N removes the first item that is equal to N. It does nothing if no item is equal to N.

For example, run_ops(["push_back 1", "push_back 2", "push_front 0", "pop_back", "push_back 3"]) is [0, 1, 3]. Each N is a 32-bit signed integer.

In computer science, "a linked list is a linear collection of data elements whose order is not given by their physical placement in memory"1. Each node keeps a link to the next node, and in a doubly linked list also a link to the node before it. So a push or a pop at an end, and the removal of a node that the code already has, take constant time. But the code finds a node only by following the links. The concept page linked list compares the two designs, and a dynamic array is the better default in most programs.

Solutions

Language Linked list Remove the first match
Python a Node class that you build; collections.deque for the ends a loop over the nodes, then unlink
JavaScript, TypeScript a Node class that you build a loop over the nodes, then unlink
Java java.util.LinkedList<Integer> list.remove(Integer.valueOf(v))
C# LinkedList<int> list.Remove(v)
Go container/list a loop, then l.Remove(e)
Rust std::collections::LinkedList<i32> split_off, pop_front and append
C a struct node with malloc and free a loop, then unlink and free
C++ std::list<int> std::ranges::find, then erase
Bash three arrays of node indexes a loop, then unlink and unset
  • Python. Python has no linked list type. The solution builds a doubly linked list with a Node class that has value, prev and next. The list keeps a head and a tail, and one unlink method removes any node and updates the ends. For a queue, use collections.deque: "Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction"2. But for a deque, "Indexed access is O(1) at both ends but slows to O(n) in the middle"2.
  • JavaScript and TypeScript. The solution builds the same Node and LinkedList classes. The list class has an iterator, so [...list] gives the items as an array.
  • Java. java.util.LinkedList is a "Doubly-linked list implementation of the List and Deque interfaces"3. addFirst, addLast, removeFirst and removeLast work at the ends. It is also a List, but "Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index"3. So a loop that calls get(i) for each i is slow.
  • C#. LinkedList<T> "Represents a doubly linked list"4. It gives its nodes as LinkedListNode<T> objects, "so insertion and removal are O(1) operations"4 when the code has the node. Remove(T) searches for the first node with the value.
  • Go. "Package list implements a doubly linked list"5. PushFront, PushBack, Front, Back and Remove work on *list.Element values. The Value field of an element has the type any, so the code needs a type assertion such as e.Value.(int) to get an int back.
  • Rust. LinkedList is "A doubly-linked list with owned nodes"6. Its own documentation says: "It is almost always better to use Vec or VecDeque because array-based containers are generally faster, more memory efficient, and make better use of CPU cache"6. It has no stable method that removes a node in the middle, so the solution uses split_off, which "Splits the list into two at the given index"6, then pop_front on the second part and append. A list that you write yourself is harder in Rust than in the other languages, because each node of a doubly linked list has two owners: the node before it and the node after it. The book about this problem says: "Yes, linked lists are so truly awful that you deal with all of these concepts in making them real"7. Its safe deque chapter also says: "Doubly-linked lists are hard, and I always make a mistake somewhere"8.
  • C. The solution builds a struct node with prev and next pointers, and gets each node from malloc. unlink_node updates the head and the tail, then frees the node. At the end, free_list reads next before it frees each node.
  • C++. "std::list is a container that supports constant time insertion and removal of elements from anywhere in the container. Fast random access is not supported"9. The solution finds the first match with std::ranges::find and erases it with the iterator.
  • Bash. Bash has no pointers or objects, so the solution keeps three indexed arrays: val, prv and nxt. A node is an index into the arrays, and the index -1 means that there is no node. This works because Bash arrays have no "requirement that members be indexed or assigned contiguously"10, so the indexes of removed nodes can stay empty.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty and push-pop: no operations, and a push followed by a pop. The result is an empty list, and the head and the tail must both be empty.
  • single and remove-only: a list of one node, where the head and the tail are the same node. After remove-only removes the only node, the next push must set both ends again.
  • remove-head and remove-tail: the removed node is at an end, so the code must move the head or the tail. A list that keeps the old tail adds the next item to a removed node.
  • pop-both-ends: a pop from the front and from the back of a list of two nodes.
  • remove-absent: the value is not in the list, and the list does not change.
  • duplicates and push-front-order: remove takes out only the first match, and push_front puts each new item before the others, so the order is reversed.
  • negative and limit: the values are negative or at the 32-bit limits, and the parse of each operation must keep them.

Pitfalls

  • Python a bounded deque drops items without an error. "Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end"2. This is correct for a buffer of the last items, but it loses data when a queue gets a maxlen by mistake:
from collections import deque

d = deque([1, 2, 3], maxlen=3)
d.append(4)
print(list(d))
d.appendleft(0)
print(list(d))
Output
[2, 3, 4]
[0, 2, 3]
  • JavaScript a removal at the end must also move the tail. The function below removes the node, but it does not change tail when the node is the last one. The next pushBack then links the new node to the removed node, and the new item is lost:
const list = { head: null, tail: null };
function pushBack(value) {
  const node = { value, next: null };
  if (list.tail === null) {
    list.head = node;
  } else {
    list.tail.next = node;
  }
  list.tail = node;
}
function removeBad(value) {
  let prev = null;
  for (let node = list.head; node !== null; prev = node, node = node.next) {
    if (node.value === value) {
      if (prev === null) {
        list.head = node.next;
      } else {
        prev.next = node.next;
      }
      return; // The fix: if (list.tail === node) list.tail = prev;
    }
  }
}
pushBack(1);
pushBack(2);
removeBad(2);
pushBack(3);
const items = [];
for (let node = list.head; node !== null; node = node.next) {
  items.push(node.value);
}
console.log(items);
Output
[ 1 ]
  • Java remove(1) removes an index, not a value. LinkedList has two methods: remove(int index) "Removes the element at the specified position in this list", and remove(Object o) "Removes the first occurrence of the specified element from this list, if it is present"3. With an int argument, Java calls the first one:
import java.util.LinkedList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    LinkedList<Integer> a = new LinkedList<>(List.of(1, 5, 7));
    a.remove(1);
    System.out.println(a);
    LinkedList<Integer> b = new LinkedList<>(List.of(1, 5, 7));
    b.remove(Integer.valueOf(1));
    System.out.println(b);
  }
}
Output
[1, 7]
[5, 7]
  • C# a node belongs to one list. AddLast(LinkedListNode<T>) throws InvalidOperationException when the "node belongs to another LinkedList"11. Remove the node from the first list before you add it to the second:
var a = new LinkedList<int>(new[] { 1, 2 });
var b = new LinkedList<int>();
var node = a.First!;
try
{
    b.AddLast(node);
}
catch (InvalidOperationException e)
{
    Console.WriteLine(e.GetType().Name);
}
a.Remove(node);
b.AddLast(node);
Console.WriteLine(string.Join(",", a) + " " + string.Join(",", b));
Output
InvalidOperationException
2 1
  • Go Remove in a loop stops the loop. Next "returns the next list element or nil"5, and after l.Remove(e) the element has no links, so e.Next() is nil and the loop ends early. Read the next element before you remove:
package main

import (
	"container/list"
	"fmt"
)

func values(l *list.List) []int {
	var out []int
	for e := l.Front(); e != nil; e = e.Next() {
		out = append(out, e.Value.(int))
	}
	return out
}

func main() {
	l := list.New()
	for _, v := range []int{1, 2, 2, 3} {
		l.PushBack(v)
	}
	for e := l.Front(); e != nil; e = e.Next() {
		if e.Value.(int) == 2 {
			l.Remove(e)
		}
	}
	fmt.Println(values(l))
	for e := l.Front(); e != nil; {
		next := e.Next()
		if e.Value.(int) == 2 {
			l.Remove(e)
		}
		e = next
	}
	fmt.Println(values(l))
}
Output
[1 2 3]
[1 3]
  • Rust two Rc links that point at each other are never freed. A safe doubly linked list often uses Rc<RefCell<Node>>, so that two nodes can own a node. But "A cycle between Rc pointers will never be deallocated. For this reason, Weak is used to break cycles"12. Below, the first two nodes link to each other with Rc in both directions, and their drop never runs. The second two use a Weak link back, and both are freed:
use std::cell::RefCell;
use std::rc::{Rc, Weak};

struct Strong {
    name: &'static str,
    other: RefCell<Option<Rc<Strong>>>,
}

impl Drop for Strong {
    fn drop(&mut self) {
        println!("drop {}", self.name);
    }
}

struct WithWeak {
    name: &'static str,
    next: RefCell<Option<Rc<WithWeak>>>,
    prev: RefCell<Weak<WithWeak>>,
}

impl Drop for WithWeak {
    fn drop(&mut self) {
        println!("drop {}", self.name);
    }
}

fn main() {
    {
        let a = Rc::new(Strong { name: "a", other: RefCell::new(None) });
        let b = Rc::new(Strong { name: "b", other: RefCell::new(Some(Rc::clone(&a))) });
        *a.other.borrow_mut() = Some(Rc::clone(&b));
        println!("strong counts: {} {}", Rc::strong_count(&a), Rc::strong_count(&b));
    }
    println!("end of the first scope");
    {
        let c = Rc::new(WithWeak { name: "c", next: RefCell::new(None), prev: RefCell::new(Weak::new()) });
        let d = Rc::new(WithWeak { name: "d", next: RefCell::new(None), prev: RefCell::new(Rc::downgrade(&c)) });
        *c.next.borrow_mut() = Some(Rc::clone(&d));
        println!("d links back: {}", d.prev.borrow().upgrade().is_some());
    }
    println!("end of the second scope");
}
Output
strong counts: 2 2
end of the first scope
d links back: true
drop c
drop d
end of the second scope
  • C a function that gets the head by value cannot change it. For a function call, "the function can modify its parameters, and those changes do not affect the arguments; C function calls are only call-by-value"13. So push_bad below changes its own copy of head, and the list of the caller stays empty. Pass a pointer to the head:
#include <stddef.h>
#include <stdio.h>

struct node {
    int value;
    struct node *next;
};

static void push_bad(struct node *head, struct node *n) {
    n->next = head;
    head = n;
}

static void push(struct node **head, struct node *n) {
    n->next = *head;
    *head = n;
}

int main(void) {
    struct node a = {1, NULL};
    struct node b = {2, NULL};
    struct node *head = NULL;
    push_bad(head, &a);
    printf("%s\n", head == NULL ? "empty" : "not empty");
    push(&head, &a);
    push(&head, &b);
    for (const struct node *n = head; n != NULL; n = n->next) {
        printf("%d\n", n->value);
    }
    return 0;
}
Output
empty
2
1
  • C++ list::remove removes every match. remove "Removes all elements that are equal to value (using operator==)"14. To remove only the first match, find it and erase it:
#include <algorithm>
#include <iostream>
#include <list>

static void print(const std::list<int> &l) {
    const char *sep = "";
    for (int x : l) {
        std::cout << sep << x;
        sep = " ";
    }
    std::cout << "\n";
}

int main() {
    std::list<int> a{4, 5, 4};
    a.remove(4);
    print(a);
    std::list<int> b{4, 5, 4};
    b.erase(std::ranges::find(b, 4));
    print(b);
}
Output
5
5 4
  • Bash unset leaves a gap in an array. "unset name[subscript] unsets the array element at index subscript"10, and the indexes after it do not move. So a loop from 0 to the count of items misses the last item. The Bash solution follows the nxt links, and does not count:
a=(10 20 30)
unset 'a[1]'
echo "${#a[@]} ${!a[*]}"
for ((i = 0; i < ${#a[@]}; i++)); do
  echo "item ${a[i]:-none}"
done
Output
2 0 2
item 10
item none

Code

The build runs the native tests of each language in a pinned toolchain.

linked_list.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-linked-list/.

from collections.abc import Iterator


class Node:
    """One node of a doubly linked list."""

    __slots__ = ("value", "prev", "next")

    def __init__(self, value: int) -> None:
        self.value = value
        self.prev: Node | None = None
        self.next: Node | None = None


class LinkedList:
    """A doubly linked list with a head and a tail.

    Python has no linked list type. collections.deque is the standard
    choice for push and pop at both ends. This class shows the links.
    """

    def __init__(self) -> None:
        self.head: Node | None = None
        self.tail: Node | None = None

    def push_front(self, value: int) -> None:
        node = Node(value)
        node.next = self.head
        if self.head is None:
            self.tail = node
        else:
            self.head.prev = node
        self.head = node

    def push_back(self, value: int) -> None:
        node = Node(value)
        node.prev = self.tail
        if self.tail is None:
            self.head = node
        else:
            self.tail.next = node
        self.tail = node

    def unlink(self, node: Node) -> None:
        # Update the head and the tail when the node is at an end.
        if node.prev is None:
            self.head = node.next
        else:
            node.prev.next = node.next
        if node.next is None:
            self.tail = node.prev
        else:
            node.next.prev = node.prev
        node.prev = node.next = None

    def remove(self, value: int) -> bool:
        node = self.head
        while node is not None:
            if node.value == value:
                self.unlink(node)
                return True
            node = node.next
        return False

    def __iter__(self) -> Iterator[int]:
        node = self.head
        while node is not None:
            yield node.value
            node = node.next


def run_ops(ops: list[str]) -> list[int]:
    """Run the operations on a new linked list and return its items."""
    items = LinkedList()
    for op in ops:
        name, _, arg = op.partition(" ")
        if name == "push_front":
            items.push_front(int(arg))
        elif name == "push_back":
            items.push_back(int(arg))
        elif name == "pop_front" and items.head is not None:
            items.unlink(items.head)
        elif name == "pop_back" and items.tail is not None:
            items.unlink(items.tail)
        elif name == "remove":
            items.remove(int(arg))
        else:
            raise ValueError(f"bad operation: {op}")
    return list(items)
test_linked_list.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-linked-list/.

import pytest

from linked_list import run_ops

CASES = {
    "deque": (["push_back 1", "push_back 2", "push_front 0", "pop_back", "push_back 3"], [0, 1, 3]),
    "remove-middle": (["push_back 1", "push_back 2", "push_back 3", "remove 2"], [1, 3]),
    "empty": ([], []),
    "push-pop": (["push_back 1", "pop_front"], []),
    "single": (["push_front 7"], [7]),
    "remove-only": (["push_back 5", "remove 5", "push_back 6"], [6]),
    "remove-head": (["push_back 1", "push_back 2", "remove 1", "push_front 0"], [0, 2]),
    "remove-tail": (["push_back 1", "push_back 2", "remove 2", "push_back 3"], [1, 3]),
    "pop-both-ends": (["push_back 1", "push_back 2", "pop_front", "pop_back", "push_front 3"], [3]),
    "remove-absent": (["push_back 1", "remove 9"], [1]),
    "duplicates": (["push_back 4", "push_back 5", "push_back 4", "remove 4"], [5, 4]),
    "push-front-order": (["push_front 1", "push_front 2", "push_front 3"], [3, 2, 1]),
    "negative": (["push_front -1", "push_back -2", "remove -1"], [-2]),
    "limit": (["push_back 2147483647", "push_front -2147483648", "remove 2147483647", "push_back 2147483647"], [-2147483648, 2147483647]),
}


@pytest.mark.parametrize("name", CASES)
def test_run_ops(name):
    ops, want = CASES[name]
    assert run_ops(ops) == want
linked_list.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

#include "linked_list.hpp"

#include <algorithm>
#include <list>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

std::vector<int> run_ops(const std::vector<std::string> &ops) {
    std::list<int> list;
    for (const auto &op : ops) {
        std::istringstream in(op);
        std::string name;
        int value = 0;
        in >> name;
        if (name == "push_front" && in >> value) {
            list.push_front(value);
        } else if (name == "push_back" && in >> value) {
            list.push_back(value);
        } else if (name == "pop_front" && !list.empty()) {
            list.pop_front();
        } else if (name == "pop_back" && !list.empty()) {
            list.pop_back();
        } else if (name == "remove" && in >> value) {
            // list.remove(value) would remove every item equal to value.
            auto it = std::ranges::find(list, value);
            if (it != list.end()) {
                list.erase(it);
            }
        } else {
            throw std::invalid_argument("bad operation: " + op);
        }
    }
    return {list.begin(), list.end()};
}
linked_list.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

#pragma once

#include <string>
#include <vector>

// run_ops runs the operations on a new std::list and returns its items.
std::vector<int> run_ops(const std::vector<std::string> &ops);
test_linked_list.cpp 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

#include "linked_list.hpp"

#include <climits>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>

static int failures = 0;

static void check(std::string_view name, const std::vector<std::string> &ops, const std::vector<int> &want) {
    if (run_ops(ops) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("deque", {"push_back 1", "push_back 2", "push_front 0", "pop_back", "push_back 3"}, std::vector<int>{0, 1, 3});
    check("remove-middle", {"push_back 1", "push_back 2", "push_back 3", "remove 2"}, std::vector<int>{1, 3});
    check("empty", {}, std::vector<int>{});
    check("push-pop", {"push_back 1", "pop_front"}, std::vector<int>{});
    check("single", {"push_front 7"}, std::vector<int>{7});
    check("remove-only", {"push_back 5", "remove 5", "push_back 6"}, std::vector<int>{6});
    check("remove-head", {"push_back 1", "push_back 2", "remove 1", "push_front 0"}, std::vector<int>{0, 2});
    check("remove-tail", {"push_back 1", "push_back 2", "remove 2", "push_back 3"}, std::vector<int>{1, 3});
    check("pop-both-ends", {"push_back 1", "push_back 2", "pop_front", "pop_back", "push_front 3"}, std::vector<int>{3});
    check("remove-absent", {"push_back 1", "remove 9"}, std::vector<int>{1});
    check("duplicates", {"push_back 4", "push_back 5", "push_back 4", "remove 4"}, std::vector<int>{5, 4});
    check("push-front-order", {"push_front 1", "push_front 2", "push_front 3"}, std::vector<int>{3, 2, 1});
    check("negative", {"push_front -1", "push_back -2", "remove -1"}, std::vector<int>{-2});
    check("limit", {"push_back 2147483647", "push_front -2147483648", "remove 2147483647", "push_back 2147483647"}, std::vector<int>{INT_MIN, INT_MAX});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
UseLinkedList.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

import java.util.LinkedList;

final class UseLinkedList {
  private UseLinkedList() {}

  /** Runs the operations on a new linked list and returns its items. */
  static int[] runOps(String[] ops) {
    LinkedList<Integer> list = new LinkedList<>();
    for (String op : ops) {
      String[] p = op.split(" ");
      switch (p[0]) {
        case "push_front" -> list.addFirst(Integer.parseInt(p[1]));
        case "push_back" -> list.addLast(Integer.parseInt(p[1]));
        case "pop_front" -> list.removeFirst();
        case "pop_back" -> list.removeLast();
        // remove(Object) removes a value. remove(int) would remove an index.
        case "remove" -> list.remove(Integer.valueOf(p[1]));
        default -> throw new IllegalArgumentException("bad operation: " + op);
      }
    }
    return list.stream().mapToInt(Integer::intValue).toArray();
  }
}
UseLinkedListTest.java 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class UseLinkedListTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("deque", new String[] {"push_back 1", "push_back 2", "push_front 0", "pop_back", "push_back 3"}, new int[] {0, 1, 3}),
        Arguments.of("remove-middle", new String[] {"push_back 1", "push_back 2", "push_back 3", "remove 2"}, new int[] {1, 3}),
        Arguments.of("empty", new String[] {}, new int[] {}),
        Arguments.of("push-pop", new String[] {"push_back 1", "pop_front"}, new int[] {}),
        Arguments.of("single", new String[] {"push_front 7"}, new int[] {7}),
        Arguments.of("remove-only", new String[] {"push_back 5", "remove 5", "push_back 6"}, new int[] {6}),
        Arguments.of("remove-head", new String[] {"push_back 1", "push_back 2", "remove 1", "push_front 0"}, new int[] {0, 2}),
        Arguments.of("remove-tail", new String[] {"push_back 1", "push_back 2", "remove 2", "push_back 3"}, new int[] {1, 3}),
        Arguments.of("pop-both-ends", new String[] {"push_back 1", "push_back 2", "pop_front", "pop_back", "push_front 3"}, new int[] {3}),
        Arguments.of("remove-absent", new String[] {"push_back 1", "remove 9"}, new int[] {1}),
        Arguments.of("duplicates", new String[] {"push_back 4", "push_back 5", "push_back 4", "remove 4"}, new int[] {5, 4}),
        Arguments.of("push-front-order", new String[] {"push_front 1", "push_front 2", "push_front 3"}, new int[] {3, 2, 1}),
        Arguments.of("negative", new String[] {"push_front -1", "push_back -2", "remove -1"}, new int[] {-2}),
        Arguments.of("limit", new String[] {"push_back 2147483647", "push_front -2147483648", "remove 2147483647", "push_back 2147483647"}, new int[] {Integer.MIN_VALUE, 2147483647}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void runOps(String name, String[] ops, int[] want) {
    assertArrayEquals(want, UseLinkedList.runOps(ops), name);
  }
}
linked_list.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

#include "linked_list.h"

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node {
    int value;
    struct node *prev;
    struct node *next;
};

struct list {
    struct node *head;
    struct node *tail;
};

static int push_front(struct list *l, int value) {
    struct node *n = malloc(sizeof *n);
    if (n == NULL) {
        return -1;
    }
    n->value = value;
    n->prev = NULL;
    n->next = l->head;
    if (l->head == NULL) {
        l->tail = n;
    } else {
        l->head->prev = n;
    }
    l->head = n;
    return 0;
}

static int push_back(struct list *l, int value) {
    struct node *n = malloc(sizeof *n);
    if (n == NULL) {
        return -1;
    }
    n->value = value;
    n->next = NULL;
    n->prev = l->tail;
    if (l->tail == NULL) {
        l->head = n;
    } else {
        l->tail->next = n;
    }
    l->tail = n;
    return 0;
}

// unlink_node takes n out of the list and frees it.
static void unlink_node(struct list *l, struct node *n) {
    if (n->prev == NULL) {
        l->head = n->next;
    } else {
        n->prev->next = n->next;
    }
    if (n->next == NULL) {
        l->tail = n->prev;
    } else {
        n->next->prev = n->prev;
    }
    free(n);
}

static void free_list(struct list *l) {
    struct node *n = l->head;
    while (n != NULL) {
        struct node *next = n->next;  // read next before free
        free(n);
        n = next;
    }
    l->head = NULL;
    l->tail = NULL;
}

static int run_one(struct list *l, const char *op) {
    char name[16];
    int value = 0;
    int got = sscanf(op, "%15s %d", name, &value);
    if (got == 2 && strcmp(name, "push_front") == 0) {
        return push_front(l, value);
    }
    if (got == 2 && strcmp(name, "push_back") == 0) {
        return push_back(l, value);
    }
    if (got == 1 && strcmp(name, "pop_front") == 0 && l->head != NULL) {
        unlink_node(l, l->head);
        return 0;
    }
    if (got == 1 && strcmp(name, "pop_back") == 0 && l->tail != NULL) {
        unlink_node(l, l->tail);
        return 0;
    }
    if (got == 2 && strcmp(name, "remove") == 0) {
        for (struct node *n = l->head; n != NULL; n = n->next) {
            if (n->value == value) {
                unlink_node(l, n);
                break;
            }
        }
        return 0;
    }
    return -1;
}

ptrdiff_t run_ops(const char *const *ops, size_t n, int *out) {
    struct list l = {NULL, NULL};
    for (size_t i = 0; i < n; i++) {
        if (run_one(&l, ops[i]) != 0) {
            free_list(&l);
            return -1;
        }
    }
    ptrdiff_t count = 0;
    for (struct node *p = l.head; p != NULL; p = p->next) {
        out[count++] = p->value;
    }
    free_list(&l);
    return count;
}
linked_list.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

#ifndef LINKED_LIST_H
#define LINKED_LIST_H

#include <stddef.h>

// run_ops runs the n operations on a new linked list and writes its items,
// from front to back, to out. out must have room for n items. It returns the
// number of items, or -1 if an operation is not valid or memory runs out.
ptrdiff_t run_ops(const char *const *ops, size_t n, int *out);

#endif
test_linked_list.c 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

#include "linked_list.h"

#include <limits.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

// C has no empty array, so an empty list is an array of one item with a count of 0.
#define CHECK(name, n, ops, m, want)                                             \
    do {                                                                         \
        const char *const o[] = ops;                                             \
        const int w[] = want;                                                    \
        int out[16] = {0};                                                       \
        ptrdiff_t got = run_ops(o, n, out);                                      \
        if (got != (m) || memcmp(out, w, (size_t)(m) * sizeof(int)) != 0) {      \
            fprintf(stderr, "case %s failed\n", name);                         \
            failures++;                                                          \
        }                                                                        \
    } while (0)

int main(void) {
    CHECK("deque", 5, L("push_back 1", "push_back 2", "push_front 0", "pop_back", "push_back 3"), 3, L(0, 1, 3));
    CHECK("remove-middle", 4, L("push_back 1", "push_back 2", "push_back 3", "remove 2"), 2, L(1, 3));
    CHECK("empty", 0, L(""), 0, L(0));
    CHECK("push-pop", 2, L("push_back 1", "pop_front"), 0, L(0));
    CHECK("single", 1, L("push_front 7"), 1, L(7));
    CHECK("remove-only", 3, L("push_back 5", "remove 5", "push_back 6"), 1, L(6));
    CHECK("remove-head", 4, L("push_back 1", "push_back 2", "remove 1", "push_front 0"), 2, L(0, 2));
    CHECK("remove-tail", 4, L("push_back 1", "push_back 2", "remove 2", "push_back 3"), 2, L(1, 3));
    CHECK("pop-both-ends", 5, L("push_back 1", "push_back 2", "pop_front", "pop_back", "push_front 3"), 1, L(3));
    CHECK("remove-absent", 2, L("push_back 1", "remove 9"), 1, L(1));
    CHECK("duplicates", 4, L("push_back 4", "push_back 5", "push_back 4", "remove 4"), 2, L(5, 4));
    CHECK("push-front-order", 3, L("push_front 1", "push_front 2", "push_front 3"), 3, L(3, 2, 1));
    CHECK("negative", 3, L("push_front -1", "push_back -2", "remove -1"), 1, L(-2));
    CHECK("limit", 4, L("push_back 2147483647", "push_front -2147483648", "remove 2147483647", "push_back 2147483647"), 2, L(INT_MIN, INT_MAX));
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
UseLinkedList.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

using System.Globalization;

public static class UseLinkedList
{
    // Runs the operations on a new linked list and returns its items.
    public static int[] Run(string[] ops)
    {
        var list = new LinkedList<int>();
        foreach (var op in ops)
        {
            var p = op.Split(' ');
            switch (p[0])
            {
                case "push_front":
                    list.AddFirst(int.Parse(p[1], CultureInfo.InvariantCulture));
                    break;
                case "push_back":
                    list.AddLast(int.Parse(p[1], CultureInfo.InvariantCulture));
                    break;
                case "pop_front":
                    list.RemoveFirst();
                    break;
                case "pop_back":
                    list.RemoveLast();
                    break;
                case "remove":
                    // Remove(T) removes the first node with the value, if there is one.
                    list.Remove(int.Parse(p[1], CultureInfo.InvariantCulture));
                    break;
                default:
                    throw new ArgumentException($"bad operation: {op}", nameof(ops));
            }
        }
        return [.. list];
    }
}
UseLinkedListTests.cs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

using Xunit;

public sealed class UseLinkedListTests
{
    public static TheoryData<string, string[], int[]> Cases => new()
    {
        { "deque", new string[] { "push_back 1", "push_back 2", "push_front 0", "pop_back", "push_back 3" }, new int[] { 0, 1, 3 } },
        { "remove-middle", new string[] { "push_back 1", "push_back 2", "push_back 3", "remove 2" }, new int[] { 1, 3 } },
        { "empty", new string[0], new int[0] },
        { "push-pop", new string[] { "push_back 1", "pop_front" }, new int[0] },
        { "single", new string[] { "push_front 7" }, new int[] { 7 } },
        { "remove-only", new string[] { "push_back 5", "remove 5", "push_back 6" }, new int[] { 6 } },
        { "remove-head", new string[] { "push_back 1", "push_back 2", "remove 1", "push_front 0" }, new int[] { 0, 2 } },
        { "remove-tail", new string[] { "push_back 1", "push_back 2", "remove 2", "push_back 3" }, new int[] { 1, 3 } },
        { "pop-both-ends", new string[] { "push_back 1", "push_back 2", "pop_front", "pop_back", "push_front 3" }, new int[] { 3 } },
        { "remove-absent", new string[] { "push_back 1", "remove 9" }, new int[] { 1 } },
        { "duplicates", new string[] { "push_back 4", "push_back 5", "push_back 4", "remove 4" }, new int[] { 5, 4 } },
        { "push-front-order", new string[] { "push_front 1", "push_front 2", "push_front 3" }, new int[] { 3, 2, 1 } },
        { "negative", new string[] { "push_front -1", "push_back -2", "remove -1" }, new int[] { -2 } },
        { "limit", new string[] { "push_back 2147483647", "push_front -2147483648", "remove 2147483647", "push_back 2147483647" }, new int[] { int.MinValue, 2147483647 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, string[] ops, int[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, UseLinkedList.Run(ops));
    }
}
linked_list.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

class Node {
  constructor(value) {
    this.value = value;
    this.prev = null;
    this.next = null;
  }
}

/** A doubly linked list with a head and a tail. JavaScript has no linked list type. */
export class LinkedList {
  head = null;
  tail = null;

  pushFront(value) {
    const node = new Node(value);
    node.next = this.head;
    if (this.head === null) {
      this.tail = node;
    } else {
      this.head.prev = node;
    }
    this.head = node;
  }

  pushBack(value) {
    const node = new Node(value);
    node.prev = this.tail;
    if (this.tail === null) {
      this.head = node;
    } else {
      this.tail.next = node;
    }
    this.tail = node;
  }

  unlink(node) {
    // Update the head and the tail when the node is at an end.
    if (node.prev === null) {
      this.head = node.next;
    } else {
      node.prev.next = node.next;
    }
    if (node.next === null) {
      this.tail = node.prev;
    } else {
      node.next.prev = node.prev;
    }
    node.prev = null;
    node.next = null;
  }

  remove(value) {
    for (let node = this.head; node !== null; node = node.next) {
      if (node.value === value) {
        this.unlink(node);
        return true;
      }
    }
    return false;
  }

  *[Symbol.iterator]() {
    for (let node = this.head; node !== null; node = node.next) {
      yield node.value;
    }
  }
}

/**
 * Runs the operations on a new linked list and returns its items.
 * @param {string[]} ops
 * @returns {number[]}
 */
export function runOps(ops) {
  const list = new LinkedList();
  for (const op of ops) {
    const [name, arg] = op.split(" ");
    if (name === "push_front") {
      list.pushFront(Number(arg));
    } else if (name === "push_back") {
      list.pushBack(Number(arg));
    } else if (name === "pop_front" && list.head !== null) {
      list.unlink(list.head);
    } else if (name === "pop_back" && list.tail !== null) {
      list.unlink(list.tail);
    } else if (name === "remove") {
      list.remove(Number(arg));
    } else {
      throw new Error(`bad operation: ${op}`);
    }
  }
  return [...list];
}
linked_list.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { runOps } from "./linked_list.js";

const cases = [
  ["deque", ["push_back 1", "push_back 2", "push_front 0", "pop_back", "push_back 3"], [0, 1, 3]],
  ["remove-middle", ["push_back 1", "push_back 2", "push_back 3", "remove 2"], [1, 3]],
  ["empty", [], []],
  ["push-pop", ["push_back 1", "pop_front"], []],
  ["single", ["push_front 7"], [7]],
  ["remove-only", ["push_back 5", "remove 5", "push_back 6"], [6]],
  ["remove-head", ["push_back 1", "push_back 2", "remove 1", "push_front 0"], [0, 2]],
  ["remove-tail", ["push_back 1", "push_back 2", "remove 2", "push_back 3"], [1, 3]],
  ["pop-both-ends", ["push_back 1", "push_back 2", "pop_front", "pop_back", "push_front 3"], [3]],
  ["remove-absent", ["push_back 1", "remove 9"], [1]],
  ["duplicates", ["push_back 4", "push_back 5", "push_back 4", "remove 4"], [5, 4]],
  ["push-front-order", ["push_front 1", "push_front 2", "push_front 3"], [3, 2, 1]],
  ["negative", ["push_front -1", "push_back -2", "remove -1"], [-2]],
  ["limit", ["push_back 2147483647", "push_front -2147483648", "remove 2147483647", "push_back 2147483647"], [-2147483648, 2147483647]],
];

for (const [name, ops, want] of cases) {
  test(name, () => {
    assert.deepEqual(runOps(ops), want);
  });
}
linked_list.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

class Node {
  value: number;
  prev: Node | null;
  next: Node | null;

  constructor(value: number) {
    this.value = value;
    this.prev = null;
    this.next = null;
  }
}

/** A doubly linked list with a head and a tail. JavaScript has no linked list type. */
export class LinkedList {
  head: Node | null = null;
  tail: Node | null = null;

  pushFront(value: number): void {
    const node = new Node(value);
    node.next = this.head;
    if (this.head === null) {
      this.tail = node;
    } else {
      this.head.prev = node;
    }
    this.head = node;
  }

  pushBack(value: number): void {
    const node = new Node(value);
    node.prev = this.tail;
    if (this.tail === null) {
      this.head = node;
    } else {
      this.tail.next = node;
    }
    this.tail = node;
  }

  unlink(node: Node): void {
    // Update the head and the tail when the node is at an end.
    if (node.prev === null) {
      this.head = node.next;
    } else {
      node.prev.next = node.next;
    }
    if (node.next === null) {
      this.tail = node.prev;
    } else {
      node.next.prev = node.prev;
    }
    node.prev = null;
    node.next = null;
  }

  remove(value: number): boolean {
    for (let node = this.head; node !== null; node = node.next) {
      if (node.value === value) {
        this.unlink(node);
        return true;
      }
    }
    return false;
  }

  *[Symbol.iterator](): Generator<number> {
    for (let node = this.head; node !== null; node = node.next) {
      yield node.value;
    }
  }
}

/** Runs the operations on a new linked list and returns its items. */
export function runOps(ops: readonly string[]): number[] {
  const list = new LinkedList();
  for (const op of ops) {
    const [name, arg] = op.split(" ");
    if (name === "push_front") {
      list.pushFront(Number(arg));
    } else if (name === "push_back") {
      list.pushBack(Number(arg));
    } else if (name === "pop_front" && list.head !== null) {
      list.unlink(list.head);
    } else if (name === "pop_back" && list.tail !== null) {
      list.unlink(list.tail);
    } else if (name === "remove") {
      list.remove(Number(arg));
    } else {
      throw new Error(`bad operation: ${op}`);
    }
  }
  return [...list];
}
linked_list.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { runOps } from "./linked_list.ts";

const cases: [string, string[], number[]][] = [
  ["deque", ["push_back 1", "push_back 2", "push_front 0", "pop_back", "push_back 3"], [0, 1, 3]],
  ["remove-middle", ["push_back 1", "push_back 2", "push_back 3", "remove 2"], [1, 3]],
  ["empty", [], []],
  ["push-pop", ["push_back 1", "pop_front"], []],
  ["single", ["push_front 7"], [7]],
  ["remove-only", ["push_back 5", "remove 5", "push_back 6"], [6]],
  ["remove-head", ["push_back 1", "push_back 2", "remove 1", "push_front 0"], [0, 2]],
  ["remove-tail", ["push_back 1", "push_back 2", "remove 2", "push_back 3"], [1, 3]],
  ["pop-both-ends", ["push_back 1", "push_back 2", "pop_front", "pop_back", "push_front 3"], [3]],
  ["remove-absent", ["push_back 1", "remove 9"], [1]],
  ["duplicates", ["push_back 4", "push_back 5", "push_back 4", "remove 4"], [5, 4]],
  ["push-front-order", ["push_front 1", "push_front 2", "push_front 3"], [3, 2, 1]],
  ["negative", ["push_front -1", "push_back -2", "remove -1"], [-2]],
  ["limit", ["push_back 2147483647", "push_front -2147483648", "remove 2147483647", "push_back 2147483647"], [-2147483648, 2147483647]],
];

for (const [name, ops, want] of cases) {
  test(name, () => {
    assert.deepEqual(runOps(ops), want);
  });
}
linked_list.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

// Package uselinkedlist runs operations on the linked list of container/list.
package uselinkedlist

import (
	"container/list"
	"strconv"
	"strings"
)

// RunOps runs the operations on a new linked list and returns its items.
func RunOps(ops []string) []int {
	l := list.New()
	for _, op := range ops {
		name, arg, _ := strings.Cut(op, " ")
		v := 0
		if arg != "" {
			n, err := strconv.Atoi(arg)
			if err != nil {
				panic("bad operation: " + op)
			}
			v = n
		}
		switch name {
		case "push_front":
			l.PushFront(v)
		case "push_back":
			l.PushBack(v)
		case "pop_front":
			l.Remove(l.Front())
		case "pop_back":
			l.Remove(l.Back())
		case "remove":
			for e := l.Front(); e != nil; e = e.Next() {
				// Value has the type any, so it needs a type assertion.
				if e.Value.(int) == v {
					l.Remove(e)
					break
				}
			}
		default:
			panic("bad operation: " + op)
		}
	}
	out := make([]int, 0, l.Len())
	for e := l.Front(); e != nil; e = e.Next() {
		out = append(out, e.Value.(int))
	}
	return out
}
linked_list_test.go 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

package uselinkedlist

import (
	"math"
	"slices"
	"testing"
)

var cases = []struct {
	name string
	ops  []string
	want []int
}{
	{"deque", []string{"push_back 1", "push_back 2", "push_front 0", "pop_back", "push_back 3"}, []int{0, 1, 3}},
	{"remove-middle", []string{"push_back 1", "push_back 2", "push_back 3", "remove 2"}, []int{1, 3}},
	{"empty", []string{}, []int{}},
	{"push-pop", []string{"push_back 1", "pop_front"}, []int{}},
	{"single", []string{"push_front 7"}, []int{7}},
	{"remove-only", []string{"push_back 5", "remove 5", "push_back 6"}, []int{6}},
	{"remove-head", []string{"push_back 1", "push_back 2", "remove 1", "push_front 0"}, []int{0, 2}},
	{"remove-tail", []string{"push_back 1", "push_back 2", "remove 2", "push_back 3"}, []int{1, 3}},
	{"pop-both-ends", []string{"push_back 1", "push_back 2", "pop_front", "pop_back", "push_front 3"}, []int{3}},
	{"remove-absent", []string{"push_back 1", "remove 9"}, []int{1}},
	{"duplicates", []string{"push_back 4", "push_back 5", "push_back 4", "remove 4"}, []int{5, 4}},
	{"push-front-order", []string{"push_front 1", "push_front 2", "push_front 3"}, []int{3, 2, 1}},
	{"negative", []string{"push_front -1", "push_back -2", "remove -1"}, []int{-2}},
	{"limit", []string{"push_back 2147483647", "push_front -2147483648", "remove 2147483647", "push_back 2147483647"}, []int{math.MinInt32, 2147483647}},
}

func TestRunOps(t *testing.T) {
	for _, c := range cases {
		if got := RunOps(c.ops); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}
linked_list.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

use std::collections::LinkedList;

/// Runs the operations on a new linked list and returns its items.
///
/// `LinkedList` has no stable method that removes an item in the middle, so
/// `remove` splits the list at the item, drops the item and joins the parts.
pub fn run_ops(ops: &[&str]) -> Vec<i32> {
    let mut list = LinkedList::new();
    for &op in ops {
        let (name, arg) = op.split_once(' ').unwrap_or((op, ""));
        let value = || arg.parse::<i32>().expect("an operation needs a 32-bit integer");
        match name {
            "push_front" => list.push_front(value()),
            "push_back" => list.push_back(value()),
            "pop_front" => {
                list.pop_front();
            }
            "pop_back" => {
                list.pop_back();
            }
            "remove" => {
                let v = value();
                if let Some(i) = list.iter().position(|&x| x == v) {
                    let mut rest = list.split_off(i);
                    rest.pop_front();
                    list.append(&mut rest);
                }
            }
            _ => panic!("bad operation: {op}"),
        }
    }
    list.into_iter().collect()
}
tests/linked_list_test.rs 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-linked-list/.

use algo_use_a_linked_list::run_ops;

#[test]
fn cases() {
    let cases: &[(&str, &[&str], &[i32])] = &[
        ("deque", &["push_back 1", "push_back 2", "push_front 0", "pop_back", "push_back 3"], &[0, 1, 3]),
        ("remove-middle", &["push_back 1", "push_back 2", "push_back 3", "remove 2"], &[1, 3]),
        ("empty", &[], &[]),
        ("push-pop", &["push_back 1", "pop_front"], &[]),
        ("single", &["push_front 7"], &[7]),
        ("remove-only", &["push_back 5", "remove 5", "push_back 6"], &[6]),
        ("remove-head", &["push_back 1", "push_back 2", "remove 1", "push_front 0"], &[0, 2]),
        ("remove-tail", &["push_back 1", "push_back 2", "remove 2", "push_back 3"], &[1, 3]),
        ("pop-both-ends", &["push_back 1", "push_back 2", "pop_front", "pop_back", "push_front 3"], &[3]),
        ("remove-absent", &["push_back 1", "remove 9"], &[1]),
        ("duplicates", &["push_back 4", "push_back 5", "push_back 4", "remove 4"], &[5, 4]),
        ("push-front-order", &["push_front 1", "push_front 2", "push_front 3"], &[3, 2, 1]),
        ("negative", &["push_front -1", "push_back -2", "remove -1"], &[-2]),
        ("limit", &["push_back 2147483647", "push_front -2147483648", "remove 2147483647", "push_back 2147483647"], &[i32::MIN, 2147483647]),
    ];
    for &(name, ops, want) in cases {
        assert_eq!(run_ops(ops), want, "{name}");
    }
}
linked_list.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-linked-list/.

# Bash has no pointers, so the list keeps its nodes in three arrays. A node
# is an index: val[i] is its value, and prv[i] and nxt[i] are the indexes of
# the nodes before and after it, or -1 at an end.

# _ll_unlink I: takes node I out of the list. It uses the arrays and the
# head and tail of the caller, because Bash variables have dynamic scope.
_ll_unlink() {
  local i=$1 p=${prv[$1]} q=${nxt[$1]}
  if ((p < 0)); then head=$q; else nxt[p]=$q; fi
  if ((q < 0)); then tail=$p; else prv[q]=$p; fi
  unset 'val[i]' 'prv[i]' 'nxt[i]'
}

# run_ops OP...
# Runs the operations on a new linked list and prints its items on one line,
# separated by spaces. Returns 2 if an operation is not valid.
run_ops() {
  local -a val=() prv=() nxt=() out=()
  local head=-1 tail=-1 id=0 op name v i
  for op in "$@"; do
    read -r name v <<<"$op"
    case $name in
      push_front)
        val[id]=$v prv[id]=-1 nxt[id]=$head
        if ((head < 0)); then tail=$id; else prv[head]=$id; fi
        head=$id id=$((id + 1)) ;;
      push_back)
        val[id]=$v nxt[id]=-1 prv[id]=$tail
        if ((tail < 0)); then head=$id; else nxt[tail]=$id; fi
        tail=$id id=$((id + 1)) ;;
      pop_front) if ((head >= 0)); then _ll_unlink "$head"; fi ;;
      pop_back) if ((tail >= 0)); then _ll_unlink "$tail"; fi ;;
      remove)
        for ((i = head; i >= 0; i = nxt[i])); do
          if ((val[i] == v)); then
            _ll_unlink "$i"
            break
          fi
        done ;;
      *)
        printf 'bad operation: %s\n' "$op" >&2
        return 2 ;;
    esac
  done
  for ((i = head; i >= 0; i = nxt[i])); do
    out+=("${val[i]}")
  done
  local IFS=' '
  printf '%s\n' "${out[*]}"
}
test_linked_list.bats 26 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-linked-list/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/linked_list.sh"
}

@test "deque" { got=$(run_ops "push_back 1" "push_back 2" "push_front 0" "pop_back" "push_back 3") || return 1; [ "$got" = "0 1 3" ]; }
@test "remove-middle" { got=$(run_ops "push_back 1" "push_back 2" "push_back 3" "remove 2") || return 1; [ "$got" = "1 3" ]; }
@test "empty" { got=$(run_ops ) || return 1; [ "$got" = "" ]; }
@test "push-pop" { got=$(run_ops "push_back 1" "pop_front") || return 1; [ "$got" = "" ]; }
@test "single" { got=$(run_ops "push_front 7") || return 1; [ "$got" = "7" ]; }
@test "remove-only" { got=$(run_ops "push_back 5" "remove 5" "push_back 6") || return 1; [ "$got" = "6" ]; }
@test "remove-head" { got=$(run_ops "push_back 1" "push_back 2" "remove 1" "push_front 0") || return 1; [ "$got" = "0 2" ]; }
@test "remove-tail" { got=$(run_ops "push_back 1" "push_back 2" "remove 2" "push_back 3") || return 1; [ "$got" = "1 3" ]; }
@test "pop-both-ends" { got=$(run_ops "push_back 1" "push_back 2" "pop_front" "pop_back" "push_front 3") || return 1; [ "$got" = "3" ]; }
@test "remove-absent" { got=$(run_ops "push_back 1" "remove 9") || return 1; [ "$got" = "1" ]; }
@test "duplicates" { got=$(run_ops "push_back 4" "push_back 5" "push_back 4" "remove 4") || return 1; [ "$got" = "5 4" ]; }
@test "push-front-order" { got=$(run_ops "push_front 1" "push_front 2" "push_front 3") || return 1; [ "$got" = "3 2 1" ]; }
@test "negative" { got=$(run_ops "push_front -1" "push_back -2" "remove -1") || return 1; [ "$got" = "-2" ]; }
@test "limit" { got=$(run_ops "push_back 2147483647" "push_front -2147483648" "remove 2147483647" "push_back 2147483647") || return 1; [ "$got" = "-2147483648 2147483647" ]; }
@test "bad-operation" { if run_ops "insert 1" 2>/dev/null; then return 1; fi; }
@test "many" { local -a ops=(); local k; for k in $(seq 300); do ops+=("push_back $k"); done; got=$(run_ops "${ops[@]}") || return 1; [ "$(wc -w <<<"$got")" -eq 300 ]; [ "${got%% *}" = 1 ]; }

References

  1. Linked list, Wikipedia, Introduction
  2. The Python Standard Library, collections, deque objects
  3. Java SE 25 API, Class LinkedList, Class description; remove(int index); remove(Object o)
  4. .NET API reference, LinkedList<T> Class, Definition; Remarks
  5. Go standard library, package list, Overview; type Element; func (*Element) Next
  6. Rust standard library, Struct LinkedList, Description; split_off
  7. Learning Rust With Entirely Too Many Linked Lists, Introduction
  8. Learning Rust With Entirely Too Many Linked Lists, A Bad Safe Deque
  9. cppreference.com, std::list, Description
  10. Bash Reference Manual, 6.7 Arrays
  11. .NET API reference, LinkedList<T>.AddLast Method, AddLast(LinkedListNode<T>), Exceptions
  12. Rust standard library, Module rc, Module description
  13. cppreference.com, C other operators, Function call
  14. cppreference.com, std::list::remove, remove_if, Description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source