A stack is implemented with an array of ‘A[0...N – 1]’ and a variable ‘pos’.…
2020
A stack is implemented with an array of ‘A[0...N – 1]’ and a variable ‘pos’. The push and pop operations are defined by the following code.
push (x)
A[pos] ← x
pos ← pos – 1
end push
pop ( )
pos ← pos + 1
return A[pos]
end pop Which of the following will initialize an empty stack with capacity N for the above implementation ?
- A.
pos ← –1
- B.
pos ← 0
- C.
pos ← 1
- D.
pos ← N – 1
Attempted by 464 students.
Show answer & explanation
Correct answer: D
The push operation writes to A[pos] and then decrements pos, indicating the stack grows downwards from higher indices. Since valid array indices range from 0 to N-1, initializing pos at the highest index ensures space for all elements. Starting at N-1 allows the first element to be stored at A[N-1], with subsequent pushes filling indices downwards to 0.
A video solution is available for this question — log in and enroll to watch it.