leetcode Min Stack
题目连接
https://leetcode.com/problems/min-stack/
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.
class MinStack { public: void push(int x) { if (val.empty() || x <= val.top()) val.push(x); num.push(x); } void pop() { if (num.top() <= val.top()) val.pop(); num.pop(); } int top() { return num.top(); } int getMin() { return val.top(); } private: stack<int> num; stack<int> val; };
By: GadyPu 博客地址:http://www.cnblogs.com/GadyPu/ 转载请说明