{
  "id": "linked-list",
  "title": "Linked List",
  "lang": "en",
  "source_lang": "en",
  "summary": "A linked list is a sequential data structure whose elements are connected by references, allowing local insertion and removal without shifting neighboring elements.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "Linked sequence",
    "chained list"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/linked-list/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/linked-list/",
      "json": "https://aiwiki.page/zh/linked-list.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "A linked list is a data structure that represents a sequence as a collection of nodes connected by references. Each node contains a value, or a reference to a value, and one or more links identifying other nodes. Unlike an array, a linked list does not require successive elements to occupy successive memory locations: its order is determined by links rather than by physical placement.\n\nLinked lists are important because they separate the logical arrangement of data from its storage layout. Once the relevant nodes are known, many insertions, removals, and rearrangements require changing only a fixed number of links. This flexibility comes at a cost: finding a position generally requires traversal, and links consume memory and often reduce locality. The structure therefore illustrates a central distinction in computer science between the cost of locating information and the cost of modifying it.\n\nLinked lists appear in language runtimes, operating-system kernels, hash tables, caches, and symbolic computation. Their practical behavior depends on the list variant, memory-management model, interface, and hardware. A theoretically constant-time update is not necessarily a fast operation in an application, and a sequence abstraction need not be implemented as a linked list."
    },
    {
      "heading": "Nodes, links, and representation invariants",
      "text": "The simplest linked list is a singly linked chain. A node contains a payload and a next link. An external reference, conventionally called the head, identifies the first node; following next repeatedly visits subsequent nodes. In a null-terminated representation, the last node’s link contains a distinguished null value, and an empty list has a null head. For example, the logical sequence \\(a,b,c\\) can be represented as head → [a | next] → [b | next] → [c | null].\n\nA link is commonly a pointer, but it need not be a machine address. It may instead be an array index, an offset within a memory region, or a runtime-managed object reference. This distinction matters when data must survive relocation or be stored outside a process’s address space. An index-based list can keep all nodes in one array while still linking them in an arbitrary logical order. Such a representation remains linked because the successor is selected through a stored link, not calculated from the element’s position in the sequence.\n\nCorrectness depends on representation invariants: conditions that must hold whenever the structure is exposed to an operation. For a conventional finite, null-terminated singly linked list, following links from the head must reach null without revisiting a node. Every encountered link must designate a valid node or null. If the list stores a tail reference, it must identify the last reachable node, whose successor is null. If it stores a length, that number must equal the number of reachable nodes. Extra bookkeeping can accelerate queries, but every mutation must preserve it.\n\nA sentinel node is a structural node that does not represent an ordinary element. A dummy node before the first element lets insertion and deletion at the front use much the same logic as operations in the middle. In a circular representation, a sentinel can mark both the beginning and the end; an empty circular list may consist of the sentinel linked to itself. Sentinels simplify boundary cases but must not be confused with payload-bearing nodes.\n\nNode identity is distinct from element value. Two nodes can contain equal values while occupying different positions, and removing one does not imply removing the other. Conversely, a node may remain at the same address while its payload changes. Interfaces that expose node handles make this distinction explicit. Interfaces that expose only values can conceal it, but their implementations still have to distinguish the identity and lifetime of each node from the meaning of the data stored inside it."
    },
    {
      "heading": "Traversal, insertion, deletion, and splicing",
      "text": "Traversal starts at a known node and repeatedly follows its successor. Searching by value compares each visited payload with a target; accessing an element by position counts links from a starting point. Neither operation can normally jump directly to an arbitrary position. A traversal may also retain the previous node, which is useful because a singly linked list does not provide a direct route backward.\n\nInsertion after a known node p requires a new node q and two conceptual assignments:\n\nq.next = p.next\np.next = q\n\nThe order matters: the old successor must remain available until it has been recorded in q. Insertion at the front is similar, except that the head reference replaces p.next. Appending is constant-time if a valid tail reference is maintained; without one, a singly linked list must normally be traversed to find its last node. Allocation and payload construction are separate costs from these link changes.\n\nDeleting the node after p redirects the predecessor around the removed node:\n\nq = p.next\np.next = q.next\n\nThe implementation must then handle the removed node’s lifetime. It may destroy and free the node, return it to a pool, or transfer ownership to the caller. If q was the tail, the stored tail must become p. Removing the first node changes the head instead. In a singly linked list, possession of a target node alone generally does not provide enough information for ordinary constant-time removal: its predecessor, or a reference to the link that points to it, is also needed.\n\nA frequently described shortcut copies the successor’s value into the target and then removes the successor. This does not implement general deletion of the target node. It fails for the last node, changes the relationship between identities and values, may require an expensive or invalid payload assignment, and can violate expectations held by external references. It is useful only under restricted assumptions.\n\nSplicing transfers an existing node or chain by rewiring boundary links rather than copying its elements. Given suitable boundary references, a chain can be detached from one list and attached to another with a fixed number of pointer changes. However, an interface may also need to discover the chain’s end, count its elements, update ownership metadata, or check allocator compatibility. Those additional requirements can make a particular splice operation linear even though its link manipulation is constant-time.\n\nA doubly linked list makes ordinary removal from a known node easier by storing both predecessor and successor links. Its extra information reduces the need to search for neighbors, but each insertion or removal must update both directions consistently."
    },
    {
      "heading": "Complexity and hardware performance",
      "text": "The standard analysis of linked-list operations uses a model in which reading or writing a link takes constant time. Under that model, traversal and unsuccessful search through \\(n\\) nodes take \\(\\Theta(n)\\) time. Accessing the element at zero-based position \\(i\\) in a singly linked list takes \\(\\Theta(i+1)\\) time from the head. In a doubly linked list with both endpoints available, traversal can begin at the nearer end, giving \\(\\Theta(\\min(i+1,n-i))\\) access time.\n\nThe usual bounds distinguish locating a position from updating it:\n\nOperation | Typical linked-list cost | Important condition\nRead the first element | \\(O(1)\\) | Head is stored\nSearch for a value | \\(O(n)\\) | No auxiliary search index\nInsert at the front | \\(O(1)\\) | Node creation treated separately\nAppend to a singly linked list | \\(O(1)\\) | Tail is maintained\nRemove a singly linked list’s last element | \\(O(n)\\) | Its predecessor must be found\nRemove a known doubly linked node | \\(O(1)\\) | Node belongs to the list\nFind the length | \\(O(1)\\) or \\(O(n)\\) | Depends on stored bookkeeping\n\nThese are time-complexity bounds, not direct measurements of elapsed time. A contiguous array can often be scanned much faster than a linked list containing the same values. Successive array accesses exhibit spatial locality and can benefit from prefetching and vectorized execution. A linked traversal performs dependent loads: the address of the next node may not become known until the current node has been fetched. Misses in the CPU cache can therefore dominate execution.\n\nThe space complexity of an ordinary list is \\(\\Theta(n)\\), but constant factors are significant. On a machine with eight-byte pointers, a singly linked node containing an eight-byte value requires sixteen bytes before allocator overhead or additional alignment effects. A doubly linked version requires at least twenty-four bytes under the same simple layout assumptions. These figures are illustrative rather than universal: pointer compression, tagged representations, payload alignment, and runtime headers can change them.\n\nA dynamic array offers constant-time indexed access and amortized constant-time appending, although an individual growth operation may relocate many elements. Linked lists avoid shifting all later elements during a local insertion, but finding that location can erase the advantage. Repeated traversal is especially costly: a loop that requests list positions \\(0,1,\\ldots,n-1\\) independently can perform \\(\\Theta(n^2)\\) work, whereas one continuous traversal takes \\(\\Theta(n)\\).\n\nMeaningful performance comparisons therefore consider element size, allocation strategy, traversal frequency, mutation locations, and handle stability. The broad claim that linked lists are “better for insertion” is incomplete without specifying how insertion positions are obtained and what the competing representation must move."
    },
    {
      "heading": "Major variants and their trade-offs",
      "text": "Singly linked lists minimize per-node linkage and naturally support forward traversal. They are particularly convenient for operations concentrated at the head. A stack, for example, can push and pop nodes there without maintaining a tail. A queue can use a head for removal and a tail for insertion. Its transition from one element to zero must reset both references consistently; otherwise the tail may continue pointing to a removed node.\n\nDoubly linked lists add a prev link to every node. If node \\(x\\) precedes node \\(y\\), consistency normally requires both \\(x.\\text{next}=y\\) and \\(y.\\text{prev}=x\\). Bidirectional traversal and removal from a known node become straightforward. The disadvantages are extra storage and more link updates. A corrupted forward link may also disagree with a still-valid backward link, leaving a structure that behaves differently depending on traversal direction.\n\nA circular linked list connects the last node back to the first, either directly or through a sentinel. There is no null successor marking the end, so traversal must stop when it returns to a designated starting point. Circular lists suit cyclic processing and permit certain concatenation operations with few link changes. They also make accidental infinite traversal easy if stopping conditions assume a null-terminated chain. Circularity is intentional here and is not itself evidence of corruption.\n\nAn intrusive list embeds linkage fields inside the objects being organized, instead of allocating a separate wrapper node for each object. This can avoid wrapper allocations and allow constant-time removal using an object reference. One object can belong to several lists if it contains a distinct linkage field for each membership. A single linkage field cannot normally represent membership in multiple independent lists at once. The surrounding system must also ensure that an object outlives every list membership that refers to it.\n\nUnrolled lists store several elements in each linked block. They reduce the number of links and allocations per element and improve locality within blocks, but insertion inside a block may require moving several values. Occupancy rules and splitting policies determine their practical behavior. Other representations encode links as offsets or combine several logical pieces of linkage into one field. XOR-linked lists, for example, encode predecessor and successor addresses together, but complicate traversal, debugging, garbage collection, and compatibility with pointer models.\n\nA skip list adds multiple levels of forward links to support search. In its standard randomized form, it provides expected logarithmic search, insertion, and deletion under appropriate assumptions. This is more than a compact variation of ordinary sequential traversal: the added links form an auxiliary navigation structure. As with trees and hash tables, faster location depends on maintaining information beyond the basic list order."
    },
    {
      "heading": "Algorithms on linked sequences",
      "text": "Many familiar algorithms must be adapted to the fact that linked lists expose successors rather than constant-time indexed positions. Sequential filtering, mapping, and accumulation are natural: each node is visited once, and results are either collected elsewhere or incorporated into an accumulator. Algorithms whose efficiency depends on jumping repeatedly to arbitrary indices usually need a different strategy or a different representation.\n\nReversing a singly linked list in place is a standard example of careful link manipulation. The algorithm maintains references to the processed prefix, the current node, and the unprocessed suffix:\n\nprevious = null\ncurrent = head\nwhile current != null:\n    following = current.next\n    current.next = previous\n    previous = current\n    current = following\nhead = previous\n\nA useful loop invariant states that previous heads the reversed processed prefix while current heads the still-unprocessed suffix. Saving following before overwriting current.next prevents loss of access to that suffix. The algorithm takes \\(\\Theta(n)\\) time and \\(O(1)\\) auxiliary space. A stored tail must also be adjusted, typically to the old head.\n\nMerge sort is well suited to linked lists because two sorted chains can be merged by repeatedly selecting their front nodes. No random access is required, and nodes can be relinked rather than copied. Dividing a list into approximately equal halves and merging recursively gives the recurrence\n\n\\[T(n)=2T(n/2)+\\Theta(n),\\]\n\nand therefore \\(\\Theta(n\\log n)\\) time. A top-down implementation normally uses \\(O(\\log n)\\) call-stack space. Bottom-up implementations merge runs of increasing length and can avoid recursive calls. Choosing an element from the left run first when keys compare equal preserves stability.\n\nTwo references moving at different speeds support several useful algorithms. To find a middle position, one advances one node per step and the other advances two; when the faster reference reaches the end, the slower is near the middle. This technique can also split a chain for sorting. Boundary details determine which middle node is selected when the length is even.\n\nFloyd’s cycle-detection algorithm uses the same speed difference to detect an unintended cycle with \\(O(1)\\) extra space. If a reachable cycle exists, the two references eventually meet inside it. Resetting one to the head and advancing both one step at a time identifies the cycle’s entry under the standard procedure. If the noncyclic prefix has length \\(\\mu\\) and the cycle has length \\(\\lambda\\), detection takes \\(O(\\mu+\\lambda)\\) time. A visited-node set is an alternative, trading extra memory for explicit records of previously seen identities.\n\nSortedness alone does not make binary search efficient on an ordinary list. A midpoint cannot be fetched in constant time. Procedures that reduce comparisons by repeatedly locating midpoints still incur substantial traversal; the logarithmic access advantage of an array does not follow merely from having sorted values."
    },
    {
      "heading": "Ownership, memory management, and language interfaces",
      "text": "A linked list’s logical operations interact closely with node ownership. In the C programming language, a typical implementation allocates nodes explicitly and releases them after removal. Losing the only pointer to an allocated chain can leak memory. Continuing to access a released node creates a dangling-pointer error, and releasing the same allocation twice can corrupt allocator state. A correct sequence of link changes is therefore insufficient unless allocation, lifetime, and cleanup are also correct.\n\nGarbage collection changes the reclamation mechanism rather than the logical structure. A removed node becomes eligible for collection when it is no longer reachable from any live root, not necessarily when it leaves one particular list. External references may keep it alive. Conversely, accidentally retaining an obsolete chain through a live head can retain all reachable nodes. Collectors that trace reachability can reclaim unreachable cycles; simple reference counting alone cannot reclaim a cycle whose members keep one another’s counts nonzero.\n\nIn functional programming, immutable singly linked lists are commonly built from an empty-list value and a constructor containing a head value and a tail list. Prepending creates one new node whose tail refers to an existing sequence. The old sequence remains available, so the structure is a persistent data structure with shared tails. If xs represents \\(b,c\\), constructing \\(a::xs\\) does not require copying \\(b\\) and \\(c\\). Appending to an immutable singly linked list, however, normally copies the left-hand chain because its final link cannot be changed.\n\nSharing affects interface guarantees. A mutable node exposed through several references permits an update through one reference to become visible through others, an instance of aliasing. Immutable lists avoid that form of structural interference, although their payloads may themselves refer to mutable objects. Exclusive-ownership systems take another approach by restricting simultaneous mutable access. Doubly linked structures are especially demanding because their bidirectional references must be reconciled with lifetime and ownership rules.\n\nStandard-library names reflect interface choices rather than one universal list abstraction. C++ provides std::forward_list for singly linked storage and std::list for doubly linked storage. Java’s LinkedList is doubly linked, whereas Python’s built-in list is a resizable array. The name “list” alone therefore does not identify memory layout or operation costs. Implementations can also differ over stored lengths, iterator behavior, and allocation policy.\n\nProof methods make ownership assumptions explicit. Separation logic, introduced in the early 2000s, provides assertions for disjoint portions of mutable memory and recursive descriptions of linked chains. In formal verification, such descriptions help establish that a routine preserves shape, does not lose nodes, and changes only the memory it owns. Acyclicity, valid references, and disjointness often matter as much as the final sequence of values."
    },
    {
      "heading": "Concurrent access and safe reclamation",
      "text": "When several threads can access a mutable list, the sequence of pointer updates becomes part of the correctness problem. An insertion that is valid in a single-threaded program may expose a partially initialized node or lose another thread’s update. Concurrent computing therefore requires both a rule for coordinating logical changes and a rule for when removed nodes may be reclaimed.\n\nA straightforward solution uses a mutual-exclusion lock around each operation or around the entire list. The lock can protect links, size metadata, and endpoint references together. Finer-grained locking permits more overlap but introduces additional obligations, including a consistent lock-acquisition order to avoid deadlock. Protecting only the assignment that changes a link may be insufficient if another thread can remove the node before the assignment or reclaim it during traversal.\n\nNonblocking algorithms often use compare-and-swap: an atomic operation that updates a location only if it still contains an expected value. A linked stack can prepare a new node pointing to the observed head, then atomically attempt to replace that head. If another thread changed it, the operation retries with a new observation. Correct publication also requires memory-ordering rules so that a thread seeing the new head sees the node’s initialized contents.\n\nA major difficulty is the ABA problem. A thread observes an address \\(A\\), another thread removes the associated node, and subsequent activity causes the same address to appear again. A comparison can then succeed even though the underlying history changed. Whether this causes failure depends on the algorithm, but address equality alone does not establish uninterrupted identity. Version tags can help distinguish states, subject to representation and wraparound considerations.\n\nMemory reclamation is a separate problem. Unlinking a node does not prove that no other thread still holds a pointer to it. Hazard pointers let threads publish references that reclamation must respect. Epoch-based techniques defer reclamation until readers that might have observed an older state are no longer active. Read-copy-update, widely used in Linux, supports patterns in which readers traverse accessible data while updaters postpone reclamation until an appropriate grace period has elapsed. Each method imposes its own rules on readers and updaters.\n\nProgress guarantees also require precise terminology. Lock-free algorithms guarantee system-wide progress despite delays to individual participants; wait-free algorithms provide a bounded-step completion guarantee for each operation under their model. Merely using an atomic pointer does not establish either property. Allocation, reclamation, retry loops, and auxiliary locks can affect the guarantee of the complete implementation, not just the code that changes the head."
    },
    {
      "heading": "Applications and the choice of representation",
      "text": "Linked lists are most useful when an application already possesses references to the objects it must move or remove. In that situation, constant-time local rewiring can be valuable without an accompanying search. When operations are dominated by sequential scans or indexed lookups, arrays or other compact representations often offer a better combination of access cost and memory behavior.\n\nA common application combines a hash table with a doubly linked list to implement a least-recently-used cache. The table maps keys to nodes, avoiding a linear search. Accessing an entry moves its node to the most-recent end; eviction removes a node from the least-recent end. With expected constant-time table operations, lookup and recency updates can have expected constant-time cost. The list records order, while the hash table supplies direct location. Neither structure alone provides both capabilities as naturally.\n\nHash-table collision handling provides another use. Under separate chaining, each bucket holds a collection of entries, often represented by a linked list. Insertion and removal can be simple, and entries need not move merely because another entry is deleted. However, linked nodes add allocation and locality costs. Separate chaining is not synonymous with linked lists: bucket collections can use arrays or other structures, and open-addressed hash tables avoid per-bucket chains entirely.\n\nWithin an operating system, intrusive lists organize objects whose identity and lifetime are managed elsewhere, including work items and resource records. The Linux kernel’s list facilities include circular doubly linked structures with embedded links. Such designs permit an object to participate in several organizational relationships through separate link fields. They also demand strict discipline around initialization, membership, locking, and object destruction.\n\nGraph adjacency lists are another important terminology distinction. An adjacency list records the neighbors of each vertex, but the records do not have to be linked lists. Arrays, dynamic arrays, and compressed layouts are common alternatives. In sparse-graph processing, contiguous neighbor storage can improve traversal substantially. Similarly, a queue, stack, or ordered collection is an abstract interface, not a commitment to linked allocation.\n\nLinked free lists can track available blocks in memory pools, sometimes storing the link inside a block while it is unused. This avoids a separate bookkeeping allocation, but overwritten links can compromise the pool. Compact alternatives include bitmaps and indexed free-slot arrays. At larger scales, a database or file system may connect records or storage blocks through persistent identifiers; when those links form a chain, traversal inherits the same sequential dependence, potentially with storage access rather than memory latency as its dominant cost."
    },
    {
      "heading": "Historical development and influence",
      "text": "Linked-list techniques emerged in early symbolic computing, where programs needed to represent expressions whose size and shape could change during execution. Early numerical programming often emphasized fixed-format records and arrays, while symbolic reasoning required convenient insertion, deletion, and sharing among variable-size structures. Linking separately stored pieces provided a way to represent these changing relationships without relocating all neighboring data.\n\nWork by Allen Newell, Cliff Shaw, and Herbert A. Simon on the Information Processing Language in the mid-1950s was central to early list processing. IPL was developed in connection with symbolic artificial-intelligence research, including the Logic Theory Machine. Its list-processing facilities helped make complex symbolic structures practical on machines with limited memory. Historical accounts commonly associate this work with the emergence of linked-list programming, although list representations developed across several related systems rather than through one modern library-style definition.\n\nJohn McCarthy’s development of Lisp beginning in the late 1950s gave linked structures a particularly influential form. His 1960 paper on recursive functions and symbolic expressions presented the foundations of a language in which symbolic data and program structure were closely connected. A Lisp cons cell contains two fields, traditionally accessed through car and cdr. A proper list is formed by a chain of cons cells whose cdr fields eventually reach the empty list.\n\nCons cells are more general than ordinary singly linked list nodes. Their fields can refer to other cons cells and atoms, permitting trees, shared structures, dotted pairs, and cyclic graphs. A proper list is therefore one disciplined arrangement within a broader representation. This distinction helped connect list processing with recursion, symbolic manipulation, interpreters, and automatic storage management. Recursive definitions of operations on an empty list or a head-and-tail pair remain a standard way to explain structural computation.\n\nAs programming languages and libraries matured, linked lists became a canonical example in the study of algorithms and data structures. They expose distinctions that are easy to obscure in higher-level interfaces: value versus identity, location versus access path, logical removal versus physical reclamation, and asymptotic cost versus hardware performance. Their small local update rules also make them useful test cases for program verification and concurrency research.\n\nTheir place in production software changed as processor speed increasingly outpaced main-memory access and cache locality became more important. This did not invalidate the abstract complexity analysis; it showed the limits of treating every memory access as equally expensive. Contemporary implementations consequently include pooled nodes, intrusive links, block-based sequences, and array-backed indices. Each preserves selected advantages of linking while changing the storage organization, ownership rules, or access pattern that determines its actual cost."
    }
  ],
  "links": [
    "data-structure",
    "array-data-structure",
    "computer-science",
    "time-complexity",
    "cpu-cache",
    "space-complexity",
    "dynamic-array",
    "stack-data-type",
    "queue-data-type",
    "loop-invariant",
    "merge-sort",
    "binary-search",
    "c-programming-language",
    "garbage-collection",
    "functional-programming",
    "aliasing",
    "formal-verification",
    "concurrent-computing",
    "deadlock",
    "linux",
    "hash-table",
    "operating-system",
    "database",
    "file-system",
    "john-mccarthy",
    "lisp-programming-language",
    "recursion",
    "algorithm"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}