The problem. Build a stack on top of a plain array. Support push(x), pop() (return the removed value, or -1 if the stack is empty), top() (return the top value, or -1 if empty), isEmpty() and size().
push(10) push(20) top() -> 20
pop() -> 20 pop() -> 10
pop() -> -1 (empty) isEmpty() -> trueThe whole question is which end of the array is the top. Pick the wrong end and every operation moves every element.
Members only · free account
The rest of this lesson, with 5 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++, opens with a free account.
Not ready yet? The Arrays course is free to read, no account needed.
In the rest of this lesson