Programming Search⌘K

Conceptcore

Linked list

Also called singly linked list, doubly linked list, circular linked list, intrusive list, cons list, LinkedList, std::list, container/list.

A linked list keeps each item in its own node with a link to the next node. It inserts and removes at a known node in constant time, but it reaches item i only by following i links.

Applies to
core-languages

Idea

A linked list stores a sequence as a chain of separate nodes. Wikipedia defines it: "a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next"1. It adds: "In its most basic form, each node contains data, and a reference (in other words, a link) to the next node in the sequence"1. The program keeps a reference to the first node, the head, and the last node has an empty link, such as null, None or NULL.

The order lives in the links, not in the memory addresses. So the program can add or remove an item by changing one or two links, and no other item moves. But the program cannot go to item i in one step. It starts at the head and follows i links.

# Each node holds one item and a link to the next node. None ends the list.
class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

def show(head):
    out = []
    while head is not None:
        out.append(head.value)
        head = head.next
    return out

# Build 1 -> 2 -> 4 by adding at the front, which changes only one link.
head = None
for v in (4, 2, 1):
    head = Node(v, head)
print(show(head))

# Insert 3 after the node that holds 2. The program needs that node, then it changes two links.
two = head.next
two.next = Node(3, two.next)
print(show(head))

# Remove the node after 1. No item moves; the link skips the node.
head.next = head.next.next
print(show(head))

# Reaching item i means following i links from the head.
def nth(head, i):
    steps = 0
    while i > 0:
        head, i, steps = head.next, i - 1, steps + 1
    return head.value, steps

print(nth(head, 2))
Output
[1, 2, 4]
[1, 2, 3, 4]
[1, 3, 4]
(4, 2)

Each change touches only the links next to it. The insert makes one node and changes the link of the node that holds 2. The remove changes the link of the head, so the node that holds 2 is no longer in the chain. To read item 2, nth follows two links.

How it works

Nodes and links. A node is a record with an item and one or more links. A link is a pointer or reference to another node. The head is a reference to the first node, and an empty list is a head with no node. Many implementations also keep a reference to the last node, the tail, so that an append takes one step, and a count, so that the length takes one step.

Singly and doubly linked. In a singly linked list, each node links to the next node only, so a walk goes in one direction. Wikipedia describes the other form: "In a 'doubly linked list', each node contains, besides the link to the next node, a second link field pointing to the 'previous' node in the sequence"1. With the second link, a program can walk backward and can remove a node when it has only that node. In a singly linked list, a remove needs the node before the one to remove.

Insert and remove. To insert node n after node p, set the link of n to the old next node of p, then set the link of p to n. To remove the node after p, set the link of p to the node after that one. In a doubly linked list, the program also updates the back links. The order of these steps matters: if the program changes the link of p first, it loses the rest of the list.

Circular lists and sentinels. In a circular list, the last node links back to the first node: "It is a list where the last node pointer points to the first node"1. A sentinel is an extra node that holds no item. Wikipedia explains the reason: "This convention simplifies and accelerates some list-handling algorithms, by ensuring that all links can be safely dereferenced"1. With a sentinel, every list, even an empty one, has a first and a last node. The Linux kernel uses both. Its list "is circular in nature. This means that to get from the head node to the tail, we can just travel one edge backwards"2, and the list head is a node with no item. The C example uses this design: an insert and a remove need no special case for the ends.

Internal and external storage. A list can keep the item in the node or keep a reference to the item. Wikipedia calls these "internal storage" and "external storage"1. An intrusive list goes further: the link fields are part of the item. The kernel declares a node "by adding a struct list_head member to the data structure you wish to be contained in the list", and explains: "Linux chooses this approach because it allows for generic list modification code regardless of what data structure is contained within the list"2. An intrusive list makes no allocation for an insert, and one item can be in several lists at the same time.

Iterators and positions. A position in a linked list is a reference to a node, not an index. Because no item moves, a position stays good while the program changes other parts of the list. cppreference says of std::list: "Adding, removing and moving the elements within the list or across several lists does not invalidate the iterators or references. An iterator is invalidated only when the corresponding element is deleted"3. A program must still take care when it removes the node that it stands on. See iterators.

In languages

LanguageVerdictNote
PythonIdiom
C++Standard library
JavaStandard library
CIdiom
C#Standard library
JavaScriptIdiom
TypeScriptIdiomTypeScript has no linked list type. A program declares a node type such as { value: T; next: Node<T> | null } and links plain objects, as in JavaScript. No example file exists.
GoStandard library
RustStandard library
KotlinStandard libraryOn the JVM, Kotlin uses java.util.LinkedList. The Kotlin standard library has ArrayDeque but no linked list of its own. No example file exists because kotlinc is not installed.
SQLIdiomA table can store the key of the next row in a column, and a recursive common table expression follows the links. Most schemas use an ordering column instead.
BashDoes not applyBash values cannot refer to each other, so it has no links. Indexed arrays are its only sequence.
PowerShellStandard library[System.Collections.Generic.LinkedList[T]] gives the .NET doubly linked list with AddFirst, AddAfter and Remove. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup. The DOM links sibling nodes with nextSibling, but HTML has no list type for data.
CSSDoes not applyCSS style rules have no data structures.
Regular expressionsDoes not applyA regular expression matches text. It has no data structures.
Language Verdict Mechanism
Python idiom a class with value and next; collections.deque is a doubly linked list of blocks
JavaScript idiom objects such as { value, next }; no built-in linked list
TypeScript idiom a node type such as { value: T; next: Node<T> | null }
Java stdlib java.util.LinkedList, a doubly linked List and Deque
Kotlin stdlib java.util.LinkedList on the JVM; ArrayDeque is the usual queue
C# stdlib LinkedList<T> with LinkedListNode<T> nodes
Go stdlib container/list, a doubly linked list of *Element nodes
Rust stdlib std::collections::LinkedList; a hand-written list uses Option<Box<Node>>
C idiom a struct with a pointer to the next node, or an intrusive list_head
C++ stdlib std::list (doubly linked) and std::forward_list (singly linked)
Bash n/a no references between values; indexed arrays only
PowerShell stdlib [System.Collections.Generic.LinkedList[T]] from .NET
SQL idiom a table with a column that holds the key of the next row, read with a recursive query
Regex n/a a pattern matches text and has no data structures
HTML n/a markup; the DOM links sibling nodes, but HTML has no list type
CSS n/a style rules have no data structures

The library lists are doubly linked. Java's LinkedList is a "Doubly-linked list implementation of the List and Deque interfaces", and "Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index"4. .NET says: "LinkedList provides separate nodes of type LinkedListNode, so insertion and removal are O(1) operations"5. Go says: "Package list implements a doubly linked list"6. C++ has both forms: std::forward_list "is implemented as a singly-linked list. Compared to std::list this container provides more space efficient storage when bidirectional iteration is not needed"7.

Rust has a linked list but tells programmers not to use it in most cases: "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"8. Its collection guide gives the cases for a LinkedList, and the last one is: "You are absolutely certain you really, truly, want a doubly linked list"9. Python has no plain linked list class. Its deque supports "memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction"10, and it is built from linked blocks. The source says: "Data for deque objects is stored in a doubly-linked list of fixed length blocks. This assures that appends or pops never move any other data elements besides the one being appended or popped"11.

The example files show these forms. Python shows collections.deque at both ends, rotate and maxlen. JavaScript builds a list from plain objects, reverses it in place and finds a loop with a slow and a fast pointer. Java shows LinkedList as a list and a deque, a ListIterator that inserts as it walks and the exception when a loop changes the list behind its iterator. C# shows LinkedListNode<T>, AddAfter and a node that belongs to one list at a time. Go shows container/list with MoveToFront and the correct way to remove nodes while it walks. Rust writes a stack of Option<Box<Node>> and reverses it, then joins two LinkedList values. C builds an intrusive circular list with a sentinel, as the Linux kernel does. C++ shows splice, erase in a loop, forward_list and list::sort. The task use a linked list runs the same operations on a list in ten languages.

PythonGitHub
from collections import deque

# collections.deque is a doubly linked list of fixed-size blocks.
# appendleft and popleft change the front without moving the other items.
d = deque([2, 3])
d.appendleft(1)
d.append(4)
print(d)
first, last = d.popleft(), d.pop()
print(first, last, d)

# rotate moves items from one end to the other.
d = deque([1, 2, 3, 4, 5])
d.rotate(2)
print(d)

# A deque with maxlen drops items from the other end when it is full.
last3 = deque(maxlen=3)
for x in range(6):
    last3.append(x)
print(last3)

# A plain list moves every item for an insert at index 0. deque does not.
lst = list(range(5))
lst.insert(0, -1)
dq = deque(range(5))
dq.appendleft(-1)
print(lst == list(dq), dq[0], dq[-1])
Output
deque([1, 2, 3, 4])
1 4 deque([2, 3])
deque([4, 5, 1, 2, 3])
deque([3, 4, 5], maxlen=3)
True -1 4
  • Verdict: idiom. Python has no plain linked list class, so a program writes a node class, as in the Idea block. collections.deque is a doubly linked list of blocks: appendleft, popleft and pop change the ends without moving the other items, rotate moves items from one end to the other, and maxlen drops items from the far end.
#include <forward_list>
#include <iostream>
#include <iterator>
#include <list>

template <typename C>
void show(const char* name, const C& c) {
    std::cout << name << ':';
    for (const auto& x : c) {
        std::cout << ' ' << x;
    }
    std::cout << '\n';
}

int main() {
    std::list<int> a{1, 2, 3};
    std::list<int> b{10, 20};
    auto two = std::next(a.begin());

    // splice moves the nodes of b into a. No item is copied, and iterators stay valid.
    auto ten = b.begin();
    a.splice(two, b);
    show("a", a);
    std::cout << "b size " << b.size() << ", *two " << *two << ", *ten " << *ten << '\n';

    // erase returns the iterator after the removed node, so a loop can remove as it walks.
    for (auto it = a.begin(); it != a.end();) {
        if (*it % 2 == 1) {
            it = a.erase(it);
        } else {
            ++it;
        }
    }
    show("even", a);

    // forward_list is singly linked, so it inserts and erases after a position.
    std::forward_list<int> f{1, 2, 3};
    f.insert_after(f.before_begin(), 0);
    f.erase_after(f.begin());
    f.reverse();
    show("forward_list", f);

    // A list sorts by relinking its nodes. std::sort needs random access and does not accept it.
    std::list<int> s{5, 3, 4, 1};
    s.sort();
    show("sorted", s);
}
Output
a: 1 10 20 2 3
b size 0, *two 2, *ten 10
even: 10 20 2
forward_list: 3 2 0
sorted: 1 3 4 5
  • Verdict: stdlib. std::list::splice moves the nodes of b into a without a copy, and the iterators two and ten stay valid. erase returns the next iterator, so a loop can remove as it walks. std::forward_list is singly linked and works after a position. list::sort relinks the nodes, because std::sort needs random access.
JavaGitHub
import java.util.LinkedList;
import java.util.ListIterator;

public class Main {
    public static void main(String[] args) {
        // LinkedList is a doubly linked list. It is both a List and a Deque.
        LinkedList<String> list = new LinkedList<>();
        list.add("b");
        list.addFirst("a");
        list.addLast("c");
        System.out.println(list + " " + list.getFirst() + " " + list.getLast());

        // A ListIterator can insert and remove at its position while it walks the list.
        ListIterator<String> it = list.listIterator();
        while (it.hasNext()) {
            String s = it.next();
            if (s.equals("b")) {
                it.remove();
                it.add("B1");
                it.add("B2");
            }
        }
        System.out.println(list);

        // As a Deque, the list works as a stack and as a queue.
        LinkedList<Integer> q = new LinkedList<>();
        q.offer(1);
        q.offer(2);
        q.push(0);
        System.out.println(q + " " + q.poll() + " " + q.pollLast() + " " + q);

        // A change to the list outside the iterator makes the iterator fail.
        try {
            for (String s : list) {
                if (s.equals("a")) {
                    list.remove(s);
                }
            }
        } catch (java.util.ConcurrentModificationException e) {
            System.out.println("ConcurrentModificationException");
        }
    }
}
Output
[a, b, c] a c
[a, B1, B2, c]
[0, 1, 2] 0 2 [1]
ConcurrentModificationException
  • Verdict: stdlib. java.util.LinkedList is a doubly linked List and Deque. A ListIterator removes and inserts at its position while it walks. push, offer, poll and pollLast use both ends. A remove through the list, not the iterator, makes the for loop throw ConcurrentModificationException.
#include <stddef.h>
#include <stdio.h>

/* An intrusive, circular, doubly linked list with a sentinel, in the style of the Linux kernel. */
struct list_head {
    struct list_head *next, *prev;
};

static void list_init(struct list_head *head) {
    head->next = head;
    head->prev = head;
}

/* Insert node between prev and next. The sentinel removes all special cases for the ends. */
static void list_insert(struct list_head *node, struct list_head *prev, struct list_head *next) {
    node->prev = prev;
    node->next = next;
    prev->next = node;
    next->prev = node;
}

static void list_add_tail(struct list_head *node, struct list_head *head) {
    list_insert(node, head->prev, head);
}

static void list_del(struct list_head *node) {
    node->prev->next = node->next;
    node->next->prev = node->prev;
    node->next = node->prev = NULL;
}

/* The node is a member of the item, so the list never allocates. */
struct task {
    int id;
    struct list_head link;
};

#define task_of(ptr) ((struct task *)((char *)(ptr) - offsetof(struct task, link)))

static void show(const struct list_head *head) {
    for (const struct list_head *p = head->next; p != head; p = p->next) {
        printf("%d ", task_of(p)->id);
    }
    printf("| empty=%d\n", head->next == head);
}

int main(void) {
    struct list_head run_queue;
    list_init(&run_queue);
    show(&run_queue);

    struct task tasks[3] = {{.id = 10}, {.id = 20}, {.id = 30}};
    for (int i = 0; i < 3; i++) {
        list_add_tail(&tasks[i].link, &run_queue);
    }
    show(&run_queue);

    list_del(&tasks[1].link);
    show(&run_queue);

    /* Walking backwards uses prev. The last node is one step from the sentinel. */
    printf("last=%d\n", task_of(run_queue.prev)->id);
    return 0;
}
Output
| empty=1
10 20 30 | empty=0
10 30 | empty=0
last=30
  • Verdict: idiom. C has no list type. This list is intrusive, circular and doubly linked, with a sentinel head, in the style of the Linux kernel. The links are a member of each task, so the list never allocates, and offsetof turns a link back into its task. The empty test is head->next == head.
using System;
using System.Collections.Generic;

class Program
{
    static string Show<T>(LinkedList<T> list) => string.Join(",", list);

    static void Main()
    {
        // LinkedList<T> is doubly linked. Each LinkedListNode<T> knows its list and its neighbors.
        var list = new LinkedList<string>(new[] { "a", "c" });
        LinkedListNode<string> a = list.First!;
        LinkedListNode<string> b = list.AddAfter(a, "b");
        list.AddLast("d");
        Console.WriteLine($"{Show(list)} {list.Count} {b.Previous!.Value} {b.Next!.Value}");

        // With a node in hand, Remove and AddFirst are O(1) and move no other item.
        list.Remove(b);
        Console.WriteLine($"{Show(list)} {b.List == null}");
        list.AddFirst(b);
        Console.WriteLine(Show(list));

        // A node belongs to one list at a time. Adding it to a second list throws.
        var other = new LinkedList<string>();
        try
        {
            other.AddLast(b);
        }
        catch (InvalidOperationException e)
        {
            Console.WriteLine(e.GetType().Name);
        }

        // Find walks from the head and returns the first node with the value.
        Console.WriteLine($"{list.Find("c")?.Next?.Value} {list.Find("z") == null}");
    }
}
Output
a,b,c,d 4 a c
a,c,d True
b,a,c,d
InvalidOperationException
d True
  • Verdict: stdlib. LinkedList is doubly linked, and AddAfter returns the new LinkedListNode, which knows its neighbors. Remove with a node takes constant time and sets the node's List to null. A node can be in one list only, so adding it to a second list throws InvalidOperationException. Find walks from the head.
JavaScriptGitHub
// A singly linked list as plain objects: { value, next }. null ends the list.
function fromArray(items) {
  let head = null;
  for (let i = items.length - 1; i >= 0; i--) {
    head = { value: items[i], next: head };
  }
  return head;
}

function toArray(head) {
  const out = [];
  for (let n = head; n !== null; n = n.next) out.push(n.value);
  return out;
}

// Reverse in place: turn each link around. No node is copied.
function reverse(head) {
  let prev = null;
  while (head !== null) {
    const next = head.next;
    head.next = prev;
    prev = head;
    head = next;
  }
  return prev;
}

const list = fromArray([1, 2, 3, 4]);
const last = list.next.next.next;
const rev = reverse(list);
console.log(toArray(rev), rev === last, list.next);

// Floyd's cycle test: a slow and a fast pointer meet only if the list has a loop.
function hasCycle(head) {
  let slow = head;
  let fast = head;
  while (fast !== null && fast.next !== null) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow === fast) return true;
  }
  return false;
}

const loop = fromArray([1, 2, 3]);
console.log(hasCycle(loop));
loop.next.next.next = loop.next; // the last node now points back to the second node
console.log(hasCycle(loop));
Output
[ 4, 3, 2, 1 ] true null
false
true
  • Verdict: idiom. JavaScript has no linked list type, so a list is a chain of plain objects. The reverse turns each link around, so the old last node becomes the head and the old head links to null. Floyd's test with a slow and a fast pointer finds the loop that the program makes.
package main

import (
	"container/list"
	"fmt"
)

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

func main() {
	// container/list is a doubly linked list. Each *Element is a node.
	l := list.New()
	a := l.PushBack("a")
	b := l.PushBack("b")
	l.PushBack("c")
	fmt.Println(values(l), l.Len())

	// Moving a node changes only links. A cache moves each used key to the front this way.
	l.MoveToFront(b)
	fmt.Println(values(l))
	l.InsertAfter("a2", a)
	fmt.Println(values(l))

	// To remove while walking, save Next before Remove, because Remove clears the links.
	for e := l.Front(); e != nil; {
		next := e.Next()
		if s := e.Value.(string); len(s) == 2 || s == "c" {
			l.Remove(e)
		}
		e = next
	}
	fmt.Println(values(l), l.Len())

	// Without the saved Next, the loop stops after the first Remove.
	l2 := list.New()
	for _, s := range []string{"x", "y", "z"} {
		l2.PushBack(s)
	}
	n := 0
	for e := l2.Front(); e != nil; e = e.Next() {
		l2.Remove(e)
		n++
	}
	fmt.Println(n, l2.Len())
}
Output
[a b c] 3
[b a c]
[b a a2 c]
[b a] 2
1 2
  • Verdict: stdlib. container/list is a doubly linked list. MoveToFront and InsertAfter change only links. A loop that saves Next before Remove removes every matching element. A loop that calls Next after Remove stops after one element, because Remove clears the links, so 2 of 3 items stay.
RustGitHub
use std::collections::LinkedList;

// A singly linked stack. Each node owns the rest of the list through a Box.
struct Node {
    value: i32,
    next: Option<Box<Node>>,
}

struct Stack {
    head: Option<Box<Node>>,
}

impl Stack {
    fn new() -> Self {
        Stack { head: None }
    }

    fn push(&mut self, value: i32) {
        let old = self.head.take();
        self.head = Some(Box::new(Node { value, next: old }));
    }

    fn pop(&mut self) -> Option<i32> {
        self.head.take().map(|node| {
            self.head = node.next;
            node.value
        })
    }

    // Reverse in place by moving each Box to a new head. No node is copied.
    fn reverse(&mut self) {
        let mut prev = None;
        let mut cur = self.head.take();
        while let Some(mut node) = cur {
            cur = node.next.take();
            node.next = prev;
            prev = Some(node);
        }
        self.head = prev;
    }

    fn to_vec(&self) -> Vec<i32> {
        let mut out = Vec::new();
        let mut cur = &self.head;
        while let Some(node) = cur {
            out.push(node.value);
            cur = &node.next;
        }
        out
    }
}

fn main() {
    let mut s = Stack::new();
    for v in 1..=4 {
        s.push(v);
    }
    println!("{:?}", s.to_vec());
    s.reverse();
    println!("{:?}", s.to_vec());
    println!("{:?} {:?}", s.pop(), s.to_vec());

    // std::collections::LinkedList can join two lists in constant time.
    let mut a: LinkedList<i32> = LinkedList::from([1, 2]);
    let mut b: LinkedList<i32> = LinkedList::from([3, 4]);
    a.append(&mut b);
    println!("{:?} {}", a, b.len());
}
Output
[4, 3, 2, 1]
[1, 2, 3, 4]
Some(1) [2, 3, 4]
[1, 2, 3, 4] 0
  • Verdict: stdlib. A hand-written singly linked stack uses Option<Box>, and take moves each Box, so push, pop and reverse copy no node. std::collections::LinkedList::append moves all nodes of b into a and leaves b empty.
  • Cons lists. The list of Lisp and Haskell is a singly linked list of immutable pairs. A new item at the front shares the old list as its tail. Wikipedia says that "if a new node is added at the beginning of a list, the former list remains available as the tail of the new one"1.
  • Stacks and queues. "Both stacks and queues are often implemented using linked lists, and simply restrict the type of operations which are supported"1. A stack uses the head only. A queue adds at the tail and removes at the head.
  • Unrolled lists. "An unrolled linked list is a linked list in which each node contains an array of data values"1. The Python deque is an example. It uses fewer links and keeps nearby items together in memory.
  • Skip lists. "The skip list is a linked list augmented with layers of pointers for quickly jumping over large numbers of elements"1. A search takes logarithmic time on average.
  • Arrays of nodes. A program can keep the nodes in an array and use indices as links. Wikipedia notes that the link fields "may be stored in a separate array with the same indices as the data records"1. This form needs no allocation per node and works in languages without pointers.
  • XOR lists. "A technique known as XOR-linking allows a doubly linked list to be implemented using a single link field in each node", but it "requires the ability to do bit operations on addresses"1.

Pitfalls

  • Indexing in a loop. get(i) on a Java LinkedList walks from an end, so a for loop over i takes quadratic time. Use an iterator.
  • A lost tail. An insert that changes the link of the old node before it saves the old next link cuts the list. Save the next link first.
  • A remove during a walk. In Go, Remove clears the links of the removed element, so a loop that calls e.Next() after Remove(e) stops at once. The Go example removes 1 of 3 items with this bug. Save the next element first. In Java, a change to the list outside the iterator makes the next call to the iterator throw ConcurrentModificationException. In C++, use the iterator that erase returns.
  • Null links. Code that follows a link without a check fails at the end of the list or on an empty list. A sentinel removes this case. See null references.
  • Cycles. A bug that links a node back to an earlier node makes a walk loop forever. Floyd's test moves one pointer by one link and another by two links, and they meet only if the list has a cycle. The JavaScript example shows it.
  • Memory in C. Each node is a separate allocation. A program must free each node once, must not use a node after it frees it, and must not free a node that is still in a list. See use after free.
  • Ownership in Rust. A doubly linked list has two links to each node, so it does not fit the rule of one owner. Safe Rust code uses Option<Box<Node>> for a singly linked list, and the standard LinkedList uses unsafe code inside. See ownership.
  • Deep recursion. A recursive function, or a destructor that drops one node and then the next, uses one stack frame per node. A long list can overflow the stack.

Cost

Operation Singly linked Doubly linked Dynamic array
get item i linear in i linear in the distance to the nearer end constant
add or remove at the front constant constant linear
add at the end constant with a tail reference constant amortized constant
insert or remove at a known node constant (after a node) constant linear
find a value linear linear linear
memory per item the item and one link the item and two links the item

The table hides the cost of memory access. Wikipedia says: "Arrays have better cache locality compared to linked lists"1. A walk over a linked list loads one node at a time from places all over memory, while a walk over an array reads one block. The links also cost space: Wikipedia notes that this "often makes them impractical for lists of small data items such as characters or Boolean values, because the storage overhead for the links may exceed" the size of the data1. For most work, a dynamic array is faster even for inserts in the middle, until the list is large. A linked list wins when the program keeps references to nodes and inserts or removes at those nodes, as in a cache that moves each used item to the front.

History

Linked lists are older than most programming languages. Wikipedia says: "The first implementation of linked listing in the computer-science context was developed in 1955–1956 by Allen Newell, Cliff Shaw, and Herbert A. Simon at RAND Corporation and Carnegie Mellon University as the primary data structure for their Information Processing Language (IPL)"1. IPL "included features to facilitate AI programming, specifically problem solving, such as lists, dynamic memory allocation, data types, recursion"12. The authors used it for early artificial intelligence programs such as the Logic Theory Machine1. Newell and Simon later won the ACM Turing Award for having "made basic contributions to artificial intelligence, the psychology of human cognition, and list processing"1.

IPL influenced Lisp12, which made the singly linked list of cons cells its main data structure in 1958. See list. File systems and operating systems also used linked lists: "Many modern operating systems use doubly linked lists to maintain references to active processes, threads, and other dynamic objects"1. Later, the cost of cache misses grew compared to the cost of a computation, and libraries such as Rust's started to advise array-based containers for most uses8.

References

  1. Linked list, Wikipedia, Introduction; History; Basic concepts and nomenclature; Tradeoffs; Related data structures
  2. Linked Lists in Linux, The Linux Kernel documentation, Linux implementation of doubly linked lists; Declaring a node
  3. std::list, cppreference.com, Introduction
  4. Class LinkedList, Java SE 25 API, Class description
  5. LinkedList<T> Class, .NET API reference, Remarks
  6. Package list, Go standard library, Overview
  7. std::forward_list, cppreference.com, Introduction
  8. Struct LinkedList, The Rust Standard Library, Description
  9. Module collections, The Rust Standard Library, Use a LinkedList when
  10. collections, The Python Standard Library, deque objects
  11. Modules/_collectionsmodule.c, CPython source code, deque objects, the comment on the block list
  12. Information Processing Language, Wikipedia, Introduction

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)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/1MGHHC/text.yaml