ProgrammingModerate

A linked stack stores nodes with a pointer to the top. Push and pop run in O(1). What is the cost of freeing the whole stack when it has n nodes?

  1. A. O(1), because the top pointer is freed
  2. B. O(n^2), because each free walks from the top
  3. C. O(log n), because the nodes are balanced
  4. D. O(n), because each node must be freed once by walking the list

Correct answer: D. O(n), because each node must be freed once by walking the list

Each node is freed exactly once while walking the links, so the cost is linear.

More C Programming questions

Exams that ask this topic