Implement Stack
EasyP2Coding
Implement a stack of integers (last in, first out) without using a library stack type.
Implement the MyStack class:
MyStack()creates an empty stack.push(x)putsxon top.pop()removes and returns the top element, or-1if the stack is empty.peek()returns the top element without removing it, or-1if the stack is empty.isEmpty()returnstrueif the stack has no elements.size()returns the number of elements.
Every operation must run in O(1) time (amortized is fine).
Example 1
- Input
- ["MyStack","push","push","peek","pop","pop","isEmpty"] [[],[1],[2],[],[],[],[]]
- Output
- [null,null,null,2,2,1,true]
- Why
- Pop returns the most recent push first; popping an empty stack gives -1.
Constraints
- -10^9 <= x <= 10^9
- At most 10^4 calls in total.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 2 visible tests, Submit all 7. ⌘Enter runs, ⌘⇧Enter submits.