CAP7004 · Unit 2: Linear data structures
Linked lists
8 practice questions
Key points
- Insert at head is O(1); access by index is O(n)
- Doubly linked list stores prev too, O(1) delete of a known node
- Slow/fast pointers find the middle and detect cycles
- Reverse in place by re-pointing next links
A singly linked list is a chain of nodes; each holds a value and a reference next to the following node. The list is reached through its head.
class Node:
def __init__(self, v, nxt=None):
self.v = v
self.next = nxt
| Operation | Singly linked list | Dynamic array |
|---|---|---|
| Access k-th element | O(k) | O(1) |
| Insert at head | O(1) | O(n) |
| Insert at tail (no tail pointer) | O(n) | O(1) amortized |
| Delete after a known node | O(1) | O(n) |
| Search | O(n) | O(n) |
A doubly linked list adds prev, allowing O(1) deletion of a given node and backward traversal at the cost of extra memory. A circular list links the last node back to the first.
Classic techniques:
- Reverse in place: keep
prev,cur,nextand re-point each link, O(n) time, O(1) space. - Find the middle: slow pointer moves one step, fast pointer two.
- Detect a cycle (Floyd): if fast ever meets slow, a cycle exists.
- Deleting a value: walk with the node before the target, then
node.next = node.next.next.
Pitfall: forgetting to handle an empty list or deletion of the head.
Try two questions
Inserting a new node at the head of a singly linked list takes:
- O(1)
- O(n^2)
- O(n)
- O(log n)
Show the answer
A. Only the head reference and one link change.
Linked list 1->2->3->4->5. Using slow and fast pointers, the node returned as the middle holds:
- 3
- 4
- 5
- 2
Show the answer
A. Slow stops at 3 when fast reaches the end.