Linked Lists: Dynamic Memory and the Power of Pointers
What happens when your data needs to grow and shrink freely — without shifting everything around.
The Problem with Arrays
Arrays are powerful, but they have a fundamental limitation: fixed size and expensive insertions.
If you have a sorted array [10, 20, 30, 40, 50] and want to insert 25 between 20 and 30:
[10, 20, 30, 40, 50, _] ← need an extra slot ↙ ↙ ↙ [10, 20, 30, 30, 40, 50] ← shift elements right [10, 20, 25, 30, 40, 50] ← place 25 This shifting takes O(n) time. For frequent insertions and deletions at arbitrary positions, arrays are inefficient.
Linked lists solve this by abandoning contiguous memory entirely.
What Is a Linked List?
A linked list is a linear data structure where elements (nodes) are stored at scattered memory locations. Each node holds:
- Data — the value.
- Pointer (Next) — the memory address of the next node.
Node: [ data | next → ] List: [10 | →] → [20 | →] → [30 | →] → [40 | null] head tail The last node's next pointer is null (or None in Python), signaling the end of the list.
Node Structure
class Node: def __init__(self, data): self.data = data self.next = None # Pointer to the next node class LinkedList: def __init__(self): self.head = None # Points to the first node Core Linked List Operations
1. Traversal — O(n)
To visit every node, follow pointers from head to tail:
def traverse(self): current = self.head while current is not None: print(current.data) current = current.next Unlike arrays, you cannot jump directly to a position — you must follow the chain.
2. Insertion
At the Beginning — O(1)
def insert_at_head(self, data): new_node = Node(data) new_node.next = self.head # New node points to old head self.head = new_node # Update head Before: head → [20] → [30] → null Insert 10 at head: After: head → [10] → [20] → [30] → null At the End — O(n)
def insert_at_tail(self, data): new_node = Node(data) if self.head is None: self.head = new_node return current = self.head while current.next is not None: # Traverse to last node current = current.next current.next = new_node We can make this O(1) by maintaining a tail pointer.
At a Specific Position — O(n)
def insert_at_position(self, data, position): new_node = Node(data) if position == 0: new_node.next = self.head self.head = new_node return current = self.head for _ in range(position - 1): if current is None: raise IndexError("Position out of range") current = current.next new_node.next = current.next current.next = new_node 3. Deletion
From the Beginning — O(1)
def delete_at_head(self): if self.head is None: return self.head = self.head.next # Move head forward By Value — O(n)
def delete_by_value(self, target): if self.head is None: return if self.head.data == target: self.head = self.head.next return current = self.head while current.next is not None: if current.next.data == target: current.next = current.next.next # Skip the node return current = current.next Key insight: to delete a node, you update the next pointer of its predecessor to skip over it. The deleted node becomes unreachable and gets garbage collected.
4. Search — O(n)
def search(self, target): current = self.head index = 0 while current is not None: if current.data == target: return index current = current.next index += 1 return -1 No random access in linked lists — you must traverse from the head.
Complexity Summary
| Operation | Singly Linked List |
|---|---|
| Access by index | O(n) |
| Search | O(n) |
| Insert at head | O(1) |
| Insert at tail | O(n) / O(1) w/ tail pointer |
| Insert at position | O(n) |
| Delete at head | O(1) |
| Delete by value | O(n) |
| Traversal | O(n) |
Why Linked Lists Are Efficient for Insertion/Deletion
The key insight: inserting into a linked list only requires updating a pointer — no shifting.
Before: [10] → [20] → [30] Insert 25 between 20 and 30: Step 1: Create new node [25] Step 2: new_node.next = 30_node Step 3: node_20.next = new_node After: [10] → [20] → [25] → [30] Only 2 pointer updates — O(1) once you have a reference to the predecessor node. (The O(n) comes from finding that predecessor in the first place.)
Applications of Linked Lists
Linked lists are used in situations where:
- Frequent insertions/deletions happen at arbitrary positions.
- Size is unknown at compile time.
- No random access is needed.
Real-world uses:
- Undo/redo functionality — each state is a node in a list.
- Browser history — doubly linked list navigation.
- Music/playlist navigation — next and previous track.
- Memory allocation — OS free-list management uses linked lists.
- Hash table chaining — each bucket holds a linked list of entries.
- Implementing stacks and queues — using linked list as the backing store.
- Polynomial representation — each term (coefficient + exponent) is a node.
Linked List vs. Array: When to Choose Which
| Scenario | Use |
|---|---|
| Frequent random access | Array |
| Frequently insert/delete at known positions | Linked List |
| Size known in advance | Array |
| Size varies dramatically at runtime | Linked List |
| Cache-friendly iteration | Array |
| Large elements with many insertions | Linked List |
| Simple implementation | Array |
Common Linked List Problems (Interview Favorites)
- Reverse a linked list — O(n) time, O(1) space.
- Detect a cycle — Floyd's Tortoise and Hare algorithm.
- Find the middle node — Two pointers (slow and fast).
- Merge two sorted lists — Classic divide-and-conquer building block.
- Remove nth node from end — Two-pointer with a gap of n.
- Find the intersection of two lists — Length difference trick.
Summary
- A linked list is a chain of nodes, each holding data and a pointer to the next node.
- Memory is non-contiguous — nodes can be anywhere in RAM.
- Insertion and deletion are O(1) at known positions (no shifting).
- Access and search are O(n) — no random access.
- Linked lists shine when size is dynamic and insertions/deletions are frequent.
- The head pointer is your entry point; losing it means losing the entire list.
In the next post, we'll cover Linked List Deletion in depth — including all edge cases and common pitfalls.
原文:https://www.a8q9.cn/en/article/linked-lists-dynamic-memory-and-the-power-of-pointers-e55f1b.html