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?
- A. O(1), because the top pointer is freed
- B. O(n^2), because each free walks from the top
- C. O(log n), because the nodes are balanced
- 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
- A list of 10^6 nodes is built by prepending, and then each node is looked up by value in a loop. What is the total cost of 10^6 lookups?
- int p = malloc(10 sizeof p); free(p); free(p); What is the result?
- In C, which of these are true about malloc's return value (assume the request succeeds)?
- A program allocates an int array of size n with malloc(n sizeof(int)). For n = 2^31, on a platform with 32-bit sizet, what can go wrong?
- A malloc'd block of 16 bytes is written past its end by 4 bytes. What is the correct description?
- Which function call allocates storage for an array of 100 doubles, all set to 0.0, in one step?