edited by
3,408 views
3 votes
3 votes

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​​​

  1. $pos \leftarrow -1$
  2. $pos\leftarrow 0$
  3. $pos\leftarrow 1$
  4. $pos\leftarrow N-1$
edited by

3 Answers

3 votes
3 votes

Answer D.

Stack is growing downwards, and on pushing an item, the top [pos] is decrementing by one, meaning the on the topmost position [pos] will be 0, or (N - 1 - (N - 1)], so the initial value of [pos] will be N - 1

0 votes
0 votes
I think answer will be d) $pos\leftarrow N-1$

Because here the 1st element is added at the end first and we find that the pointer is decremented after it has added the element. So, here the pointer shouldhave been initiallized to N-1.
0 votes
0 votes
push (x)

A[pos] <- x

pos <- pos -1

end push

Look at the push operation. $x$ is pushed at pos, then pos is decremented.

This means if our array is $A[0,1,2,3]$ then in order to push four elements, we first we're pushing at index 3, then at index 2, then at index 1 and finally at index 0.

We have to initialize pos with the value equalling $N-1$

 

Option D
Answer:

Related questions

2 votes
2 votes
3 answers
1
6 votes
6 votes
3 answers
2
Satbir asked Jan 13, 2020
3,332 views
Of the following, which best approximates the ratio of the number of nonterminal nodes in the total number of nodes in a complete $K$-ary tree of depth $N$ ?$1/N$$N-1/N$$...
4 votes
4 votes
3 answers
3
Satbir asked Jan 13, 2020
2,953 views
Convert the pre-fix expression to in-fix $- ^{\ast} +ABC^{\ast} – DE+FG$$(A-B)^{\ast}C+(D^{\ast}E)-(F+G)$$(A+B)^{\ast}C-(D-E)^{\ast}(F+G)$$(A+B-C)^{\ast}(D-E)^{\ast}(F+...
5 votes
5 votes
3 answers
4
Satbir asked Jan 13, 2020
5,841 views
The minimum height of an AVL tree with $n$ nodes is$\text{Ceil } (\log_2(n+1))$$1.44\ \log_2n$$\text{Floor } (\log_2(n+1))$$1.64\ \log_2n$