Min Stack
Description:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
Code:
1 class MinStack { 2 public: 3 void push(int x) { 4 m_stack.push(x); 5 if (min_num.empty() || x<min_num.top()) 6 min_num.push(x); 7 else 8 min_num.push(min_num.top()); 9 } 10 11 void pop() { 12 assert( !m_stack.empty() && !min_num.empty() ); 13 m_stack.pop(); 14 min_num.pop(); 15 } 16 17 int top() { 18 assert( !m_stack.empty() ); 19 return m_stack.top(); 20 } 21 22 int getMin() { 23 return min_num.top(); 24 } 25 private: 26 stack<int>m_stack; 27 stack<int>min_num; 28 };