Skip to main content

5.1 Singly Linked Lists: Node Architecture, Traversal & Pointer Operations

📚Module 05 • Linked ListsTopic 5.1⏱️18 min read
🎯High-Yield For:Semester Exams • Technical Interviews • Engineering Foundations

💡 Core Intuition: The 3-Second Mental Model​

🍳 The Everyday Analogy: A Scavenger Hunt Across Campus​

Suppose you want to guide a friend through four hidden clues (A → B → C → D):

  • Arrays are like locker rows: All 4 envelopes must sit inside consecutive, adjacent locker numbers (100, 101, 102, 103). If someone drops an extra envelope between Locker 100 and 101, every envelope afterward must shift over by one locker!
  • Linked Lists are a scavenger hunt: Clue A can sit under a bench, containing its message plus the GPS address pointing to Clue B behind a library bookshelf, which points to Clue C, and so on. None of the hiding spots need to be physically side by side.

💻 Bridging to Computer Science: Non-Contiguous Pointer Chaining​

In RAM, a Singly Linked List (SLL) drops the requirement for a single contiguous array block. Each element resides in an independently heap-allocated Node containing:

  1. Data Field: The stored payload (e.g., int, struct).
  2. Next Link Field (next): The physical memory address of the next node in logical order—or NULL (0x0) on the final tail node to mark termination.

An external entry pointer HEAD (also called START or FIRST) stores the address of node 1, and HEAD == NULL canonically represents an Empty (Null) List.


🧩 Contiguous Arrays vs. Dynamic Linked Chains​

Static arrays suffer from two structural rigidity flaws: internal/external fragmentation (arrays cannot grow/shrink gracefully and demand a single unbroken RAM region) and O(n)\mathcal{O}(n) insertion/deletion shifting. Linked lists trade direct index arithmetic for structural elasticity:

Contiguous Array vs. Dynamic Singly Linked List

Fundamental hardware and algorithmic trade-offs between address math and pointer chasing

Contiguous Array

Static Contiguous Array

📊
Dominant Architecture / DomainDirect Indexing • Hardware Cache Locality
  • •O(1) instant random access via Base + i * W arithmetic.
  • •Zero per-element pointer overhead (100% payload storage).
  • •Exceptional CPU L1/L2 cache line spatial prefetching.
  • •Suffers from fixed sizing, external fragmentation, and O(n) head/middle shifts.
"Unbeatable read throughput and compactness when size bounds are predictable."
Linked List

Dynamic Singly Linked List

🔗
Dominant Architecture / DomainDynamic Heap Growth • O(1) Local Rewiring
  • •Grows and shrinks one node at a time across fragmented heap gaps.
  • •O(1) insertion and deletion once the predecessor pointer is known.
  • •Requires O(n) sequential traversal for lookups—no random access or binary search!
  • •Carries extra pointer metadata per node (16B per int node on 64-bit OS = 4x RAM).
"Total structural flexibility at the cost of pointer chasing and extra pointer bytes."

Engineering Trade-Off Summary Matrix​

Architectural DimensionContiguous ArraySingly Linked List
Memory LayoutSingle contiguous RAM blockScattered non-contiguous heap chunks
Random Index Access (A[i])O(1)\mathcal{O}(1) InstantaneousO(n)\mathcal{O}(n) Sequential pointer walk
Insert / Delete at HeadO(n)\mathcal{O}(n) element shiftsO(1)\mathcal{O}(1) Pointer rewire
Insert / Delete After Node locO(n)\mathcal{O}(n) element shiftsO(1)\mathcal{O}(1) Pointer rewire
Memory per int (64-bit OS)4 bytes4\text{ bytes} (00 overhead)16 bytes16\text{ bytes} (4B int+4B pad+8B ptr4\text{B int} + 4\text{B pad} + 8\text{B ptr})
CPU Cache Prefetch EfficiencyHigh (Sequential cache lines)Low (Pointer-chasing cache stalls)

🏗️ Node Anatomy, Traversal & Searching in C​

A linked list node in C is a self-referential struct—a structure whose link member points to another instance of its own struct type:

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

typedef struct Node {
int data; // 4 bytes payload (+ 4 bytes alignment padding on 64-bit)
struct Node *next; // 8 bytes forward memory address
} Node;

// Allocate & initialize a single heap node in O(1)
Node* createNode(int value) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Heap exhausted: malloc returned NULL.\n");
exit(1);
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}

Iterative vs. Recursive Traversal (while vs. Call Stack)​

Notice the sharp auxiliary-space contrast between looping with a local cursor ptr versus recursing on head->next:

// Iterative Traversal: Time = Theta(n), Auxiliary Space = Theta(1)
void traverseIterative(const Node *head) {
const Node *ptr = head;
while (ptr != NULL) {
printf("%d -> ", ptr->data);
ptr = ptr->next; // Advance pointer along chain
}
printf("NULL\n");
}

// Recursive Traversal: Time = Theta(n), Auxiliary Space = Theta(n) call-stack frames
void traverseRecursive(const Node *head) {
if (head == NULL) return; // Empty or end of list reached
printf("%d -> ", head->data); // Print before recurse -> forward order
traverseRecursive(head->next);
}

Both iterative (while (ptr != NULL)) and recursive (search(head->next, key)) searches run in O(n)\mathcal{O}(n) worst-case time. On a sorted linked list (ascending), traversal can exit early once ptr->data > key, yet worst-case complexity remains O(n)\mathcal{O}(n) because linked lists lack O(1)\mathcal{O}(1) midpoint indexing for Binary Search!

Node* searchKey(Node *head, int key) {
Node *ptr = head;
while (ptr != NULL) {
if (ptr->data == key) return ptr; // Found target address
ptr = ptr->next;
}
return NULL; // Key absent
}

➕ Pointer-Order Laws: Insertion Algorithms​

Every linked list insertion takes O(1)\mathcal{O}(1) pointer assignments once the target boundary is in hand—provided you respect one strict rule of execution order:

📐The Pointer-Ordering Law of Insertiontheorem

When splicing newNode right after an existing node loc, you MUST bind newNode->next to the trailing chain before redirecting loc->next:

newNode->next←loc->nextTHENloc->next←newNode\text{newNode->next} \leftarrow \text{loc->next} \quad\textbf{THEN}\quad \text{loc->next} \leftarrow \text{newNode}

Reversing these two lines (loc->next = newNode; first) overwrites the only saved pointer to the remainder of the list, causing an immediate irreversible Memory Leak & Tail Loss!

// Case 1: Insert at Beginning (Head) -> O(1)
// Returns updated Head pointer cleanly (or pass Node **headRef!)
Node* insertAtHead(Node *head, int key) {
Node *ptr = createNode(key);
ptr->next = head; // Point to old head first (even if NULL!)
head = ptr; // Advance external head cursor
return head;
}

// Case 2: Insert After Given Node Pointer 'loc' -> O(1)
void insertAfter(Node *loc, int key) {
if (loc == NULL) return; // Invalid target guard
Node *newNode = createNode(key);
newNode->next = loc->next; // Step 1: Preserve successor link
loc->next = newNode; // Step 2: Splice newNode cleanly
}

➖ Safe Unlinking & Heap Deallocation: Deletion Algorithms​

Removing a node requires two disciplined actions: bypassing the node in the pointer chain AND explicitly freeing its heap allocation via free() so memory does not leak indefinitely:

// Case 1: Delete at Beginning (Head) -> O(1)
Node* deleteAtHead(Node *head, int *removedVal) {
if (head == NULL) {
printf("Underflow: List is empty!\n");
return NULL;
}
Node *temp = head; // Step 1: Save node address to free!
*removedVal = temp->data;
head = head->next; // Step 2: Advance head to 2nd node
free(temp); // Step 3: Prevent heap memory leak
return head;
}

// Case 2: Delete After Given Predecessor 'loc' -> O(1)
int deleteAfter(Node *loc) {
if (loc == NULL || loc->next == NULL) {
printf("Underflow: No successor exists after loc.\n");
return -1;
}
Node *target = loc->next; // Node to remove
int item = target->data;
loc->next = target->next; // Unlink target cleanly
free(target);
return item;
}

The Constant-Time Middle-Node Deletion Trick (Without HEAD)​

Normally, deleting an arbitrary node p requires head so we can locate p's predecessor in O(n)\mathcal{O}(n) time. Exception: if p is guaranteed not to be the last node (p->next != NULL), you can overwrite p's payload with its successor's payload (p->data = p->next->data;) and unlink + free p->next in O(1)\mathcal{O}(1) time!


🏭 Real-World Production Context: Allocators, Chains & Dynamic Lists​

Singly Linked List Systems Applications

Core infrastructure relying on low-overhead O(1) head splicing and dynamic chains

🧠

Heap Free-List Allocators

malloc / jemalloc
  • Maintains freed variable-size RAM blocks as intrusive singly linked free-lists.
  • Zero external metadata per free chunk since pointers reside inside unused payload memory.
🗄️

Separate Chaining Hash Tables

Collision Buckets
  • Each hash bucket anchors a short singly linked list of colliding key-value nodes.
  • Allows dynamic resizing and O(1) head prepend upon hash collisions.
📐

Symbolic Polynomials & Sparse Vectors

CAS / Compilers
  • Represents high-degree sparse polynomials cleanly as (coeff, exponent, next) chains.
  • Avoids allocating millions of zero entries across sparse exponent ranges.
🔁

Lock-Free Treiber Stacks

Concurrency / Atomics
  • Uses Compare-And-Swap (CAS) on HEAD pointer of a singly linked list for wait-free LIFO push/pop.
  • Powers lockless task pools in multi-core runtime schedulers.

📐 Numerical Applications & Worked Examples​

Example 1: Moving the Tail Node to the Front via Two-Pointer Scan​

📐Problem Statementtheorem

Examine the C function moveLastToFront(Node *head) below, designed to relocate the final node of a singly linked list cleanly to the front:

Node* moveLastToFront(Node *head) {
Node *p, *q;
if ((head == NULL) || (head->next == NULL))
return head;
q = NULL;
p = head;
while (p->next != NULL) {
q = p;
p = p->next;
}
// STEP X: Rewire q, p, and head here!
return head;
}

Determine the exact 3 pointer assignment statements for STEP X, and verify why the (head == NULL || head->next == NULL) guard is mandatory before entering the while loop.

Step-by-Step Solution:​

  1. Loop Termination Invariant: When while (p->next != NULL) terminates on a list of ≥2\ge 2 nodes:
    • p points directly to the Tail node (p->next == NULL).
    • q trails one link behind, pointing to the Second-to-Last node (q->next == p).
  2. Three Exact Rewiring Steps (STEP X):
    • Disconnect tail p cleanly by marking q as the new tail: q->next = NULL;
    • Attach p in front of the current head: p->next = head;
    • Move head to p: head = p;
  3. Why the Early Guard Matters: If the list had 00 nodes (head == NULL), evaluating p->next would crash with a null-pointer dereference; if it had 11 node (head->next == NULL), the while loop wouldn't run, leaving q == NULL, so executing q->next = NULL would also segfault!

Example 2: Worst-Case Search Comparisons on a Sorted Singly Linked List​

📐Problem Statementtheorem

Suppose nn keys are stored in strictly ascending sorted order inside a Singly Linked List (head -> ... -> tail -> NULL). Derive the exact worst-case number of key comparisons required to determine whether a search key xx exists in the list, and explain why sorting fails to unlock O(log⁡n)\mathcal{O}(\log n) Binary Search.

Step-by-Step Solution:​

  1. Lack of Constant-Time Middle Access: Binary Search requires jumping straight to mid = (low + high) / 2 in O(1)\mathcal{O}(1) arithmetic. In a linked list, advancing n / 2 steps takes Θ(n)\Theta(n) pointer dereferences, wiping out any logarithmic advantage.
  2. Sequential Early-Exit Search: The optimal algorithm walks from head inspecting ptr->data:
    • If ptr->data == x, return ptr.
    • If ptr->data > x, exit early (return NULL).
  3. Worst Case (xx greater than tail->data, or equal to tail->data): Every single one of the nn nodes from head through tail satisfies ptr->data <= x, forcing nn key comparisons (Θ(n)\Theta(n) worst case).

Example 3: Post-Traversal Recursion Stack Output & 64-Bit Memory Budget​

📐Problem Statementtheorem

Consider the list HEAD -> [10] -> [20] -> [30] -> [40] -> NULL:

  1. Trace the exact stdout output produced by calling mystery(HEAD):
    void mystery(const Node *p) {
    if (p == NULL) return;
    mystery(p->next);
    printf("%d ", p->data);
    }
  2. On a 64-bit machine (sizeof(int) = 4, sizeof(Node*) = 8, struct size aligned to 16 bytes), calculate the total RAM required for 1,000,0001{,}000{,}000 integers in a contiguous int array versus this Singly Linked List.

Step-by-Step Solution:​

  1. Tracing mystery(HEAD): Notice printf appears after mystery(p->next):
    • Call stack winds down cleanly: mystery(10) -> mystery(20) -> mystery(30) -> mystery(40) -> mystery(NULL).
    • mystery(NULL) hits the base case and returns.
    • Frames unwind upward executing printf: outputs 40 30 20 10 (reverse tail-to-head order using O(n)\mathcal{O}(n) call stack frames!).
  2. 64-Bit RAM Budget:
    • Array: 106×4 bytes=4 MB10^6 \times 4\text{ bytes} = \mathbf{4\text{ MB}}.
    • Singly Linked List: 106×16 bytes=16 MB10^6 \times 16\text{ bytes} = \mathbf{16\text{ MB}} (400% total memory footprint—12 MB spent purely on pointers and padding!).

🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  • Null / Empty List Convention: How is an empty singly linked list identified? External pointer HEAD == NULL; on a non-empty list, the final node's next field contains NULL (0x0).
  • Pass-by-Value Trap in C insert(Node *head): Passing Node *head by value creates a local copy of the address inside the function; updating head = ptr inside a void function fails to update the caller's head unless you either return the new Node* or pass a double pointer Node **headRef!
  • Recursive vs. Iterative Reversal/Print Memory: While an iterative walk costs O(1)\mathcal{O}(1) extra RAM, recursive traversal (mystery(head->next)) allocates nn call-stack activation frames (O(n)\mathcal{O}(n) auxiliary space).
  • Binary Search Incompatibility: Even a sorted singly linked list still suffers Θ(n)\Theta(n) worst-case search complexity because middle elements cannot be indexed in O(1)\mathcal{O}(1) time.
Common Interview Traps: Architectural Trade-Offs
  • Reversing Insertion Order Loses the List: Calling loc->next = newNode; before newNode->next = loc->next; creates a self-pointing/broken link and permanently leaks the entire suffix after loc.
  • Memory Leak on deleteAtHead: Executing head = head->next; without first saving Node *temp = head; and calling free(temp) leaks the removed head node permanently on the heap.
  • Self-Looping Head Insertion: Writing head = newNode; newNode->next = head; links newNode->next onto itself, creating an infinite 1-node cycle on the next traversal!
  • Payload-Copy Deletion Edge Case: The "delete node p without head in O(1)\mathcal{O}(1)" trick (p->data = p->next->data) crashes with a null dereference whenever p is the Tail node (p->next == NULL), because there is no successor payload to copy!

🚀 Navigation & Next Steps​

With Node Architecture, Insertion/Deletion pointer laws, and Traversal fundamentals locked in, we next tackle classic single-pass pointer transformations: In-Place Reversal, Two-Pointer Fast/Slow Patterns, and Floyd's Cycle Detection.

🚀 Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚡
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

💡Help keep Binary Dose free for students, or share your articles and notes.