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 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? Correct Answer pos ← N - 1

Concept:

Usually, the empty stack is initialized with value 0 and this value increments by 1 every time we push an element on to the stack.

The code for such a stack looks like this,

push (x)

                A ← x

                pos ← pos + 1 //the initial value is incremented by 1 as element is pushed onto the stack

end push

However, in the question, when push operation takes place, the value of variable is decremented by 1 (pos – 1).  Hence, initial value of pos will have to be N-1.

Explanation

For example, if we take an array with N = 4 to represent our stack. It will be A .

Now, in order to push four elements, say x, y, z, w

  • First we will push at x index 3 which is 4 – 1
  • Then, we will decrement pos and push y at index 2 and so on.

Note that, the pop operation is also behaving inversely here.

  • In usual stack, pop would decrement value of pos.

In our case, pop is incrementing the value of pos.

Related Questions

A teacher asked the class to subtract 5 from 75.70% of the class said: 25. Their work was shown as: \(\begin{array}{*{20}{c}} {\begin{array}{*{20}{c}} 7&5 \end{array}}\\ {\underline {\begin{array}{*{20}{c}}\ { - 5} \ \ \ &{} \end{array}} }\\ {\underline {\begin{array}{*{20}{c}} 2&5 \end{array}} } \end{array}\) Which of the following describes the most appropriate remedial action that the teacher should take to clarify this misconception?
Suppose a stack implementation supports an instruction REVERSE, which reverses the order of elements on the stack, in addition to the PUSH and POP instructions. Which one of the following statements is TRUE with respect to this modified stack?