1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 2

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
OperationSingly linked listDynamic array
Access k-th elementO(k)O(1)
Insert at headO(1)O(n)
Insert at tail (no tail pointer)O(n)O(1) amortized
Delete after a known nodeO(1)O(n)
SearchO(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, next and 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

Question 1 · Tier 1, Recall

Inserting a new node at the head of a singly linked list takes:

  1. O(1)
  2. O(n^2)
  3. O(n)
  4. O(log n)
Show the answer

A. Only the head reference and one link change.

Question 2 · Tier 2, Understand

Linked list 1->2->3->4->5. Using slow and fast pointers, the node returned as the middle holds:

  1. 3
  2. 4
  3. 5
  4. 2
Show the answer

A. Slow stops at 3 when fast reaches the end.