Search code examples
stack

Where does index 0 go for a stack, top or bottom?


I am just learning stacks and I don't understand why the answer to the question below is D None of the above, I thought it was B[2, 7]. I'm getting tripped up by the "Assume that index 0 is at the bottom of the stack".

Consider the following code snippet:

1 stack = Stack()
2 stack.pop()
3 stack.push(2)
4 stack.push(7)
5 stack.push(1)
6 stack.pop()

What is stored in the stack once the above snippet has been executed? (Assume that index 0 is the bottom of the stack.)

A. [2, 7, 1]

B. [2, 7]

C. [2]

D. None of the above.


Solution

  • A stack implemented using an array would start from 0. At Line 2 stack.pop() is a case of StackUnderFlow. Considering you're trying to pop() from a stack that is empty. So in case an exception is thrown, further lines would not be executed.