AlgoLounge

Implement Stack

easy

Implement a stack data structure with the following operations:

  • push(val): Push an element onto the stack
  • pop(): Remove and return the top element from the stack
  • top(): Return the top element without removing it
  • empty(): Return whether the stack is empty

You can choose to implement the stack using either:

  1. Linked List - Each node points to the next node
  2. Circular Array - Fixed-size array with wrapping

Examples

Example 1

Input:  ["Stack", "push", "push", "top", "pop", "empty"]

[[], [1], [2], [], [], []] Output: [null, null, null, 2, 2, false]

Example 2

Input:  ["Stack", "push", "pop", "empty"]

[[], [10], [], []] Output: [null, null, 10, true]

Constraints

  • 1 <= val <= 10^9
  • At most 10^4 calls will be made to each function
  • pop and top will only be called on non-empty stacks

How the tests work: each test is a sequence of calls. operations[i] is the method called with arguments[i]; the first entry constructs the class. The expected output lists what every call returns — null for the constructor and for methods that return nothing.

TypeScript
Loading editor…
List of test cases (10)
Case 1
operations = ["Stack","push","push","top","pop","empty"]
arguments = [[],[1],[2],[],[],[]]
Case 2
operations = ["Stack","push","pop","empty"]
arguments = [[],[10],[],[]]
Case 3
operations = ["Stack","push","push","push","pop","pop","pop","empty"]
arguments = [[],["hello"],["world"],["test"],[],[],[],[]]
Case 4
operations = ["Stack","push","top","top","pop","empty"]
arguments = [[],[5],[],[],[],[]]
Case 5
operations = ["Stack","empty","push","empty","push","top"]
arguments = [[],[],[100],[],[200],[]]
Case 6
operations = ["Stack","push","push","push","push","push","pop","pop","pop","pop","pop","empty"]
arguments = [[],["a"],["b"],["c"],["d"],["e"],[],[],[],[],[],[]]
Case 7
operations = ["Stack","push","push","pop","push","pop","pop","empty"]
arguments = [[],[7],[8],[],[9],[],[],[]]
Case 8
operations = ["Stack","push","top","push","top","push","top"]
arguments = [[],["x"],[],["y"],[],["z"],[]]
Case 9
operations = ["Stack","push","push","push","top","pop","top","pop","top"]
arguments = [[],[10],[20],[30],[],[],[],[],[]]
Case 10
operations = ["Stack","push","empty","pop","empty","push","push","pop","empty"]
arguments = [[],[42],[],[],[],[50],[60],[],[]]