题解 | #包含min函数的栈#
包含min函数的栈
http://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
class Solution {
public:
//本题需要三个栈,第一个栈是真正的栈,第二个和第三个栈是辅助栈,用来在常数时间里求出最小值min
stack<int> s1,s2,s3;
void push(int value) {
s1.push(value);
while(!s2.empty()&&value>s2.top()){
int temp=s2.top();
s2.pop();
s3.push(temp);
}
s2.push(value);
while(!s3.empty()){
int temp=s3.top();
s3.pop();
s2.push(temp);
}
}
void pop() {
int temp=s1.top();
s1.pop();
while(s2.top()!=temp){
int data=s2.top();
s2.pop();
s3.push(data);
}
s2.pop();
while(!s3.empty()){
int data=s3.top();
s3.pop();
s2.push(data);
}
}
int top() {
return s1.top();
}
int min() {
return s2.top();
}
};
public:
//本题需要三个栈,第一个栈是真正的栈,第二个和第三个栈是辅助栈,用来在常数时间里求出最小值min
stack<int> s1,s2,s3;
void push(int value) {
s1.push(value);
while(!s2.empty()&&value>s2.top()){
int temp=s2.top();
s2.pop();
s3.push(temp);
}
s2.push(value);
while(!s3.empty()){
int temp=s3.top();
s3.pop();
s2.push(temp);
}
}
void pop() {
int temp=s1.top();
s1.pop();
while(s2.top()!=temp){
int data=s2.top();
s2.pop();
s3.push(data);
}
s2.pop();
while(!s3.empty()){
int data=s3.top();
s3.pop();
s2.push(data);
}
}
int top() {
return s1.top();
}
int min() {
return s2.top();
}
};