您的位置:首页 > 职场人生

可以随时查找的max栈和max队列——面试

2013-10-30 18:01 169 查看
这是面试中比较常见的题目,max队列也是编程之美里的一道题

对于max的栈,有个比较简单的办法就是,每次入栈前判断栈顶元素与正在入栈的元素哪个大,哪个大就哪个入栈

对于队列,我们知道可以用两个栈来实现,这时,我想到是否可以用栈来维护max的队列

结果是可以的,不过要用三个栈, 1 +2 ,前一个max栈+ (后一个max栈+普通的栈) ,每次寻找max都在前一个max栈和后一个max栈中找,而要更新前一个栈的时候,要把普通的栈来去更新

考虑 1,2,4,3

进1进2进4进3出1出2出4

大4大4大3

/*
10
push 1
push 2
push 4
push 2
pop
max
pop
max
pop
max
*/

#include<iostream>
#include<stack>
#include<queue>
using namespace std;

//push
//pop
//max
struct data{
int v;
};

stack<data>first,end;
stack<data>sta;

int main()
{
int n;
while(scanf("%d",&n)!=EOF){
int i,shu;data temp;
char str[10];
for(i=1;i<=n;i++){
scanf("%s",&str);

if(end.empty()&&(!sta.empty())){ //第二个堆空的时候把第一个普通堆放到第二个堆里

end.push(sta.top());
sta.pop();
first.pop();
while(!sta.empty()){
temp=end.top();
if(temp.v<sta.top().v){
temp=sta.top();
}
end.push(temp);
sta.pop();
first.pop();
}
}

if(str[1]=='u'){
scanf("%d",&shu);
temp.v=shu;
sta.push(temp);
if(!first.empty()){
if(first.top().v>temp.v)temp=first.top();
first.push(temp);
}else{
first.push(temp);
}
}else if(str[1]=='o') {
end.pop();
}else{//max
if(!first.empty()){
temp=first.top();
if(temp.v<end.top().v)temp=end.top();
}else{
temp=end.top();
}
printf("%d\n",temp.v);
}
}
}

return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐