8 Linked Lists
Linked Lists
Connecting nodes and understanding pointers. The foundation of dynamic data structures.
9 // Linked Lists: Connecting the Dots
Linked Lists were where I first felt like a “real” programmer. Pointers everywhere!
My realization: It’s all about not losing your way. Always keep a reference to where you’re going before you let go of where you are. And always use a dummy node.
9.1 Types of Linked Lists
9.1.1 1. Singly Linked List
- Each node points to the next node
- Last node points to null
- Operations: insert/delete at head/tail, search, reverse
9.1.2 2. Doubly Linked List
- Each node has pointers to both next and previous nodes
- Allows traversal in both directions
- More memory but more operations flexibility
9.1.3 3. Circular Linked List
- Last node points back to the first node
- Can be singly or doubly linked
- Useful for round-robin type operations
9.2 Time Complexity
| Operation | Time Complexity |
|---|---|
| Access | O(n) |
| Search | O(n) |
| Insertion | O(1) - at head/tail with pointer |
| Deletion | O(1) - at head/tail with pointer |
| O(n) - at arbitrary position |
9.3 Common Operations
9.3.1 Node Definition (Python)
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next9.3.2 Traversal
def traverse(head):
current = head
while current:
print(current.val)
current = current.next9.3.3 Insertion at Head
def insert_at_head(head, val):
new_node = ListNode(val)
new_node.next = head
return new_node9.3.4 Deletion by Value
def delete_node(head, val):
dummy = ListNode(0, head)
prev, current = dummy, head
while current:
if current.val == val:
prev.next = current.next
else:
prev = current
current = current.next
return dummy.next9.4 Common Patterns
- Two Pointers (Fast & Slow)
- Dummy Node for Head Modifications
- Reversing a Linked List
- Finding the Middle Node
- Detecting Cycles
9.5 Practice Problems
9.6 Tips for Interviews
- Always check for edge cases (empty list, single node, etc.)
- Use dummy nodes to simplify head modifications
- Draw diagrams for complex pointer manipulations
- Consider recursive solutions for certain problems
- Be careful with pointer assignments to avoid losing references