面试题30:包含min函数的栈
本题考查栈的使用。
C++版本
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
// 定义数据栈
stack<int> stack1;
// 定义辅助栈
stack<int> stack2;
void push(int value){
// 需要遍历辅助栈中最小的值
if(stack2.size() == 0 || value < stack2.top())
stack2.push(value);
else
stack2.push(stack2.top());
stack1.push(value);
}
// 弹出栈顶元素
void pop(){
stack1.pop();
stack2.pop();
}
int top(){
return stack1.top();
}
int min(){
return stack2.top();
}
int main()
{
push(3);
cout<<min()<<endl;
push(4);
cout<<min()<<endl;
push(2);
cout<<min()<<endl;
push(1);
cout<<min()<<endl;
pop();
cout<<min()<<endl;
pop();
cout<<min()<<endl;
push(0);
cout<<min()<<endl;
return 0;
}