Member-only story
Top Coding Algorithms — Stack
2 min readMay 8, 2020
Stack is like a list but with limited operations on it, basically the essence is last come first out. There are 2 fundamental operations on stack, push and pop. Consider we have a stack as following:
With 2 elements, now PUSH operation stacks on element on top of the existing stack:
POP operation removes the element on top of the stack and bring it back to the original stack:
Implement a Stack
Following a question on leetCode, let’s implement a customised stack in python.
Design a stack which supports the following operations.Implement the CustomStack class:- CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize.- void push(int x) Adds x to the top of the stack if the stack hasn't reached the maxSize.- int pop() Pops and returns the top…