ISRO 2020 · Arrays & Matrix Representation

MCQ · 1 mark · Problem PROG-DSTR-0100

A stack is implemented with an array 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?
  1. A
    \(\text { pos } \leftarrow-1\)
  2. B
    \(\text { pos } \leftarrow 0\)
  3. C
    \(\text { pos } \leftarrow 1\)
  4. D
    \(\text { pos } \leftarrow N-1\)

Solve it on GATE DA practice →More Basic Data Structures problems

Show the worked solutionpush writes A[pos] first and then decrements pos, so pos always points to the next free cell and the stack grows downwards from the top end of the array. pop moves pos up by one and returns that cell.For an empty stack of capacity N, the first push must write A[N-1], so pos must start at N-1. Then N pushes fill A[N-1], A[N-2], ..., A[0], and pos ends at -1 (full).Starting with pos = -1 or 0 would give room for 0 or 1 element, and pos = 1 for only 2.Answer: D

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com