两个栈实现栈内最小数据的查询,建立一个栈A存放原始数据,再利用另一个栈B存放每一次的当前栈中的最小数,当栈A要push新的数据时,首先将该数据与栈B的top值相比较,如果栈A的数据比栈B的top值小,则将该数push近栈B,否则栈B压入上一次栈顶的值,这样就记录了每一次比较的最小值。pop时也是一样栈A与栈B的top值相等时,同时pop,否则只pop栈A的top值。
#include<iostream>
#include<stack>
#include<string>
using namespace std;
class Solution{
public:
void push(int value){
StackData.push(value);
if(StackMin.empty()||value<=StackMin.top())
{
StackMin.push(value);
}
else if(value>StackMin.top())
{
StackMin.push(StackMin.top());
}
}
void pop(){
if(!StackData.empty())
{
StackData.pop();
StackMin.pop();
}
else
{
throw out_of_range("");
}
}
int top()
{
return StackData.top();
}
int getMin()
{
return StackMin.top();
}
private:
stack<int> StackData;
stack<int> StackMin;
};
static Solution obj;
int main()
{
int n,value;
string s;
cin>>n;
while(n--){
cin>>s;
if(s=="push")
{
cin>>value;
obj.push(value);
}
else if(s=="getMin")
{
cout<<obj.getMin()<<endl;
}
else
{
obj.pop();
}
}
return 0;
}
京公网安备 11010502036488号