1、好像不能用 stack 作为容器
class MaxStack {
public:
stack<int> maxsk;
stack<int> sk;
MaxStack() {
maxsk.push(INT_MIN);
}
void push(int x) {
sk.push(x);
maxsk.push(max(maxsk.top(),x));
}
int pop() {
int ret = sk.top();
sk.pop();
maxsk.pop();
return ret;
}
int top() {
return sk.top();
}
int peekMax() {
return maxsk.top();
}
int popMax() {
int ret = maxsk.top();
if(sk.top() == maxsk.top())
sk.pop();
maxsk.pop();
return ret;
}
};
/**
* Your MaxStack object will be instantiated and called as such:
* MaxStack* obj = new MaxStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->peekMax();
* int param_5 = obj->popMax();
*/
用 vector 来实现的,
class MaxStack {
public:
vector<int> sk;
MaxStack() {
}
void push(int x) {
sk.push_back(x);
}
int pop() {
int ret = sk.back();
sk.pop_back();
return ret;
}
int top() {
return sk.back();
}
int peekMax() {
return *max_element(sk.begin(), sk.end());
}
int popMax() {
auto it = max_element(sk.rbegin(),sk.rend());
int ret = *it;
sk.erase((++it).base());
//反向迭代器转化成正向迭代器。
//需要向前移动一格,再转化成正向的迭代器。
return ret;
}
};
/**
* Your MaxStack object will be instantiated and called as such:
* MaxStack* obj = new MaxStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->peekMax();
* int param_5 = obj->popMax();
*/
别人的双栈实现
class MaxStack {
stack<int> s1, s2; //s1数据栈,s2辅助栈(存储对应数据为栈顶时,栈中元素的最大值)
public:
MaxStack() {
}
void push(int x) {
s1.push(x);
if(!s2.empty() && s2.top() > x){ //栈非空,且辅助栈的栈顶元素大于x时,栈顶元素入栈
s2.push(s2.top());
}
else{
s2.push(x);
}
}
int pop() {
int curNum = s1.top();
s1.pop();
s2.pop();
return curNum;
}
int top() {
return s1.top();
}
int peekMax() {
return s2.top(); //辅助栈的栈顶元素即为栈中最大元素
}
int popMax() {
int maxNum = s2.top(); //画图即可
stack<int> temp;
while(s1.top() != maxNum) temp.push(pop()); //temp暂存栈顶到最大元素中间所有的数据
pop(); //移除最靠近栈顶的最大元素
while(!temp.empty()){ //临时栈不为空,可将临时栈中所有数据插入最大栈中
push(temp.top());
temp.pop();
}
return maxNum;
}
};