Stack Implementation

Easy~15 min

Implement a MyStack class that represents a last-in, first-out (LIFO) stack of integers.

The MyStack class should support the following operations:

  • MyStack() — Initialize an empty stack.
  • push(val) — Push the integer val onto the top of the stack.
  • pop() — Remove and return the element on top of the stack. Return -1 if the stack is empty.
  • peek() — Return the element on top of the stack without removing it. Return -1 if the stack is empty.
  • isEmpty() — Return true if the stack is empty, false otherwise.
  • size() — Return the number of elements in the stack.

Examples

Example 1
Input: ["MyStack","push","push","push","peek","pop","size","isEmpty"] [[],[1],[2],[3],[],[],[],[]]
Output: [null,null,null,null,3,3,2,false]
Explanation: MyStack stack = new MyStack(); stack.push(1); // stack: [1] stack.push(2); // stack: [1, 2] stack.push(3); // stack: [1, 2, 3] stack.peek(); // return 3 (top element) stack.pop(); // return 3, stack: [1, 2] stack.size(); // return 2 stack.isEmpty(); // return false

Constraints

  • -1000 <= val <= 1000
  • At most 1000 calls will be made to push, pop, peek, isEmpty, and size
  • pop and peek return -1 when the stack is empty
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run