Implement a stack on an array
Standard · Write code · about 15 min
Complete the class ArrayStack so it stores values in a fixed array data of capacity slots and an index top. Do not use the language's built-in list push or pop.
push(x)stores x and returns true, or returns false when the stack is full (overflow).pop()removes and returns the top value, or returns -1 when the stack is empty.peek()returns the top value without removing it, or -1 when empty.
The given runStack(capacity, ops) runs the operations and collects one result per operation (push: 1 or 0).
Example 1
Input:
[2,["push 1","push 2","push 3","peek","pop","pop","pop"]]
Output:
[1,1,0,2,2,1,-1]
push 3 finds no free slot, so it returns 0. The third pop finds the stack empty.
Example 2
Input:
[3,["push 5","peek","push 9","pop","peek"]]
Output:
[1,5,1,9,5]
Constraints
- 1 ≤ capacity ≤ 1, 000
- 1 ≤ ops.length ≤ 1, 000
- Each op is "push x" with 0 ≤ x ≤ 1, 000, "pop" or "peek"
Learn the idea first: Stacks: push, pop, peek; array and linked implementations, a visual lesson.
More Stacks: push, pop, peek; array and linked implementations problems
- Overflow handling Warm-up
- State after a sequence Warm-up
- Baseball game score Standard
- Spot the bug: pop returns the wrong value Standard
- Implement a stack with a linked list Challenge