Solution Review: Min Stack
Let's discuss the solution of the challenge posed in the previous lesson.
We'll cover the following
Solution: A two-stack class
Weāll make a new class consisting of two stacks: mainStack
and minimumStack
. The class will have the following functions:
Push()
Pop()
Min()
Letās see what each function will do:
-
Push
: Push an element to the top ofmainStack
. It compares the new value with the value at the top ofminimumStack
. If the new value is smaller, then we push the new value intominimumStack
. Otherwise, we push the minimum value at the top of theminimumStack
to itself again. -
Pop
: Pops an element from the top ofmainStack
and returns. It also pops an element from the top ofminimumStack
. -
Min
: Reads from the top of theminimumStack
. This value will be the minimum value.
Get hands-on with 1400+ tech skills courses.