Linked Lists

Linked lists are fundamental data structures that store elements in a sequence, where each element points to the next. Unlike arrays, linked lists do not require contiguous memory — nodes can reside anywhere in memory and are connected through pointers. This makes them especially useful when the collection size changes frequently and predictable memory layout is not required.

What Is a Linked List?#

A linked list is a linear data structure where elements (called nodes) are connected through pointers. Each node stores two things: the data it holds, and a pointer (reference) to the next node in the sequence. The first node is called the head; the last node's pointer is set to null, marking the end of the list.

Rendering diagram...

Key Characteristics#

PropertyDescription
Dynamic SizeCan grow or shrink at runtime without reallocation
Non-Contiguous MemoryNodes can be stored anywhere in memory
Pointer-BasedEach node contains a reference to the next node
Sequential AccessMust traverse from head to reach any element
Efficient Insertion/DeletionO(1) at the head; O(1) anywhere if you already hold a reference to the target node

Node Structure#

The building block of a linked list is the node. Each node contains two fields: the data it holds, and a next pointer that references the following node. When next is null (or None in Python), the node is the last one in the list.

Rendering diagram...

Node Implementation

The basic building block of a linked list

Basic node class in Python

Types of Linked Lists#

There are three main variants of linked lists. Each has distinct structural properties that make it better suited to certain problems.

Rendering diagram...
Rendering diagram...
Rendering diagram...
TypeDescriptionTraversalUse Cases
Singly LinkedEach node points to next onlyForward onlyStacks, simple lists
Doubly LinkedEach node points to prev and nextBoth directionsBrowser history, undo/redo
CircularLast node points back to firstContinuous loopRound-robin scheduling

Arrays vs Linked Lists#

Choosing between an array and a linked list is one of the most common trade-off decisions in data structure design. The key difference is how they store data in memory: arrays use a single contiguous block, while linked list nodes can be scattered anywhere.

Rendering diagram...
Rendering diagram...
OperationArrayLinked ListWinner
Access by indexO(1)O(n)Array
SearchO(n)O(n)Tie
Insert at beginningO(n)O(1)Linked List
Insert at endO(1)*O(n) or O(1)**Depends
Insert in middleO(n)O(n)*Linked List*
Delete at beginningO(n)O(1)Linked List
Delete at endO(1)O(n) or O(1)**Depends
Memory usageLess (no pointers)More (pointers)Array
Cache performanceBetter (contiguous)Worse (scattered)Array

* Amortized for dynamic arrays. ** O(1) with tail pointer. *** Both structures require O(n) to traverse to the position. The linked list advantage is that the insertion itself is O(1) — only two pointers change. Arrays must shift all subsequent elements, adding constant-factor overhead.

Basic Operations#

The table below summarizes the core operations on a singly linked list and their time complexities. Note that complexities marked with * or ** can be improved with extra bookkeeping (a tail pointer or a cached length).

OperationDescriptionTime Complexity
TraverseVisit each node from head to tailO(n)
Insert at HeadAdd new node at the beginningO(1)
Insert at TailAdd new node at the endO(n)*
Insert at PositionAdd new node at specific indexO(n)
Delete at HeadRemove the first nodeO(1)
Delete at TailRemove the last nodeO(n)
Delete by ValueRemove node with specific valueO(n)
SearchFind node with specific valueO(n)
Get LengthCount number of nodesO(n)**

* O(1) with tail pointer. ** O(1) if length is cached.

When to Use Linked Lists#

Not every problem calls for a linked list. Use the table below as a decision guide — and remember that in most high-level languages, the built-in array or list type is a dynamic array, not a linked list.

ScenarioUse Linked List?Reason
Frequent insertions/deletions at beginningYesO(1) vs O(n) for arrays
Unknown size, frequent size changesYesNo reallocation needed
Need to access elements by indexNoArrays have O(1) access
Memory is limitedNoLinked lists have pointer overhead
Implementing stacksYesO(1) push/pop at head
Implementing queuesYesO(1) with head and tail pointers
Cache-sensitive applicationsNoArrays have better cache locality
Need to iterate frequentlyDependsArrays slightly faster due to cache

Better Alternatives#

In practice, a linked list is often not the best tool even when its theoretical properties seem attractive. Here are common alternatives worth considering first:

If You Need...Consider Using
Fast index access + dynamic sizeDynamic Array (Python list, JavaScript array)
Fast insertion at both endsDeque (double-ended queue)
Fast lookup by valueHash Set or Hash Map
Sorted data with fast searchBalanced BST or Sorted Array

Reviewing AI-Generated Code#

Linked list bugs are subtle and silent. A single pointer assigned in the wrong order can orphan the rest of the list — no error is thrown, but data disappears. When reviewing AI-generated linked list code, pay close attention to these common failure points:

IssueWhat to CheckCommon AI Mistake
Null checksCheck node before accessing .nextAccessing node.next when node is None
Pointer updatesOrder of pointer changesLosing reference to rest of list
Edge casesEmpty list, single nodeNot handling empty list case
Memory leaksOrphaned nodes (in C/C++)Not freeing deleted nodes
Loop terminationCorrect stopping conditionOff-by-one errors in traversal

Spotting AI Linked List Bugs

Common pointer manipulation errors in AI-generated code

Correct pointer manipulation with proper order

Questions to Ask AI About Linked List Code#

When in doubt about AI-generated linked list code, prompt the AI with these targeted questions:

  1. "What happens with an empty list?" — The head is null; code must check before dereferencing.
  2. "What happens with a single-node list?" — An edge case that frequently exposes off-by-one errors.
  3. "Are pointer updates applied in the correct order?" — Updating in the wrong sequence silently drops nodes or creates a self-loop.
  4. "Does this code create a cycle?" — Verify that no node's next pointer accidentally points back to an earlier node.

Summary#

ConceptKey Takeaway
Linked ListSequential nodes connected by pointers
NodeContains data and reference to next node
Singly LinkedOne-way traversal, simpler structure
Doubly LinkedTwo-way traversal, more flexible
CircularNo null end, continuous loop
vs ArraysBetter for insertions, worse for random access
Trade-offsMemory overhead vs insertion efficiency

Linked lists form the conceptual foundation for more advanced structures like trees, graphs, and hash tables. Understanding how nodes connect through pointers — and how easily those connections can go wrong — is a skill that applies far beyond linked lists themselves. Next, let's explore each variant in more detail.