题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
提交代码:
class Solution {
public:
stack<int> s1;
stack<int> min_stack;
void push(int value) {
s1.push(value);
if (min_stack.empty())
{
min_stack.push(value);
}
else {
if (value <= min_stack.top())
{
min_stack.push(value);
}
}
}
void pop() {
if (s1.empty())
{
return ;
}
int temp = s1.top();
s1.pop();
if (temp==min_stack.top())
{
min_stack.pop();
}
}
int top() {
if (s1.empty())
{
return NULL;
}
return s1.top();
}
int min() {
if (min_stack.empty())
{
return NULL;
}
return min_stack.top();
}
};
测试案列:
int main()
{
Solution* s = new Solution();
s->push(5);
s->push(4);
s->push(2);
s->push(4);
cout << s->min() << endl;
s->pop();
s->pop();
cout << "" << endl;
system("pause");
return 0;
}
运行结果: