Topic 4 of 21 · Beginner
Linked Lists
Nodes connected by pointers — reversal, fast/slow pointers and merging.
Concept
Each node holds a value and a pointer to the next node. Insertion at a known node is O(1), but reaching index i takes O(i).
Fast & slow pointers: slow moves 1 step, fast moves 2. They meet if there is a cycle, and slow is at the middle when fast reaches the end.
A dummy head node removes edge cases when the head may change.
Complexity
| Operation | Time | Space |
|---|---|---|
| Access by index | O(n) | — |
| Insert / delete at known node | O(1) | — |
| Search | O(n) | — |
Code (Python)
class Node:
def __init__(self, val, nxt=None):
self.val, self.next = val, nxt
def reverse(head):
prev = None
while head:
head.next, prev, head = prev, head, head.next
return prev
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return FalseRemember
- Draw the pointers before coding.
- Use a dummy node for merges and deletions.
- Fast/slow pointers find middle and cycles.
Practice these interview problems
- Reverse Linked List
- Merge Two Sorted Lists
- Linked List Cycle
- Remove Nth Node From End
Lesson test
Take an 8-question test on “Linked Lists” — concepts, output prediction, bug spotting and interview questions.