题目描述:

LeetCode_155. Min Stack_数据


思路:设置两个LeetCode_155. Min Stack_数据_02LeetCode_155. Min Stack_数据_03LeetCode_155. Min Stack_数据_04,分别用于存放加入stack中的数据和stack中最小的数据。

class MinStack {
public:
/** initialize your data structure here. */
MinStack() {

}

void push(int x) {
data.push(x);
//min_data为空,则当前元素就是栈中最小的元素
if(min_data.empty())
min_data.push(x);
//和栈顶元素比较大小,决定加入的元素是什么
else{
if(x<min_data.top())
min_data.push(x);
else
min_data.push(min_data.top());
}
}

void pop() {
data.pop();
min_data.pop();
}

int top() {
if(!data.empty())
return data.top();
else
return -1;
}

int getMin() {
if(!min_data.empty())
return min_data.top();
else
return -1;
}
private:
stack<int> data;
stack<int> min_data;
};

/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/