← Back to STL Containers
Question 522
Min Stack
Min Stack
Build a classMinStackthat behaves like a normal stack of ints but can also report its smallest element in constant time —getMin()must not scan the stack. Implement these public methods: 1.void push(int x)— pushesxon top 2.void pop()— removes the top element (never called on an empty stack by the tests) 3.int top() const— returns the top element without removing it 4.int getMin() const— returns the smallest element currently in the stack 5.bool empty() const— returns true when the stack has no elements Example: afterpush(2),push(1),push(3)the test printsgetMin(), thentop(), then pops twice and printsgetMin()again, one value per line (see Expected Output). The tests printempty()as the wordstrueorfalse. Do NOT write a main function.
Expected Output:
1 3 2 true 5 5 5 5 true
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
STL ContainersStacks
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.