Core Module
12 min forge
Singly Linked List
Master the fundamental non-contiguous data structure. Learn about nodes, pointers, and iterative vs. recursive manipulation.
π Singly Linked List: Chain of Nodes
A Linked List is a linear data structure where elements are not stored at contiguous memory locations. Instead, each element is a separate Node object that contains the data and a Pointer (reference) to the next node in the sequence.
π‘ The Logic (ELI5)
Think of a Linked List as a Scavenger Hunt:
- You have a clue (Data).
- Attached to that clue is a map to the next location (Pointer).
- To get to the 5th location, you must visit locations 1, 2, 3, and 4 first. You can't just teleport there.
- If you lose the map to the next location, the rest of the hunt is lost!
π The Deep Dive
Core Properties
- Dynamic Size: Can easily grow or shrink without expensive resizing (unlike arrays).
- Non-Contiguous: Nodes can be anywhere in memory.
- Sequential Access: No random access. To find the $n^{th}$ element, you must traverse from the
head.
Complexity Analysis
| Operation | Complexity | Description |
|---|---|---|
| Access | O(n) | Must traverse from head |
| Search | O(n) | Linear search |
| Insert (Head) | O(1) | Just update the head pointer |
| Insert (Tail) | O(n) | Must find tail first (O(1) if you have tail pointer) |
| Delete (Head) | O(1) | Move head to head.next |
π οΈ Code Forge: Node & List Implementation
javascript Standard/** * A Single Node in the List */ class ListNode { constructor(value) { this.value = value; this.next = null; // Pointer to the next node } } /** * Basic Linked List Operations */ class LinkedList { constructor() { this.head = null; } // Add to the front - O(1) prepend(value) { const newNode = new ListNode(value); newNode.next = this.head; this.head = newNode; } // Reverse the list - O(n) time, O(1) space reverse() { let prev = null; let curr = this.head; while (curr) { const nextTemp = curr.next; // Store next curr.next = prev; // Reverse pointer prev = curr; // Move prev forward curr = nextTemp; // Move curr forward } this.head = prev; } }
π― Interview Pulse
Top Techniques
- Dummy Head: Use a temporary node
dummy = new ListNode(0)whosenextpoints to the head. This simplifies edge cases like deleting the head. - Two Pointers: Used for finding midpoints, detecting cycles, or finding the $k^{th}$ node from the end.
Common Questions
- Reverse a Linked List (Iterative & Recursive).
- Merge two sorted linked lists.
- Remove $n^{th}$ node from the end.
- Intersection of two linked lists.
- Palindrome Linked List. Blackwell