1. 两个栈实现队列
http://ac.jobdu.com/problem.php?pid=1512
大致思路:入队列时,将元素入栈S1,出队列时,将S2中的元素出栈即可,如果S2为空,那么将S1中【S1.size()-1】个元素出栈,加入到S2中,然后将S1中最后一个元素出栈,即完成了出队列的操作
#include <iostream>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <stack>
#include <cstring>
/* two queue construct a stack */
class queue{
private:
stack<int> s1,s2;
public:
queue(){
while(!s1.empty())
s1.pop();
while(!s2.empty())
s2.pop();
}
void add(int x){
s1.push(x);
}
int remove(){
int x;
if(!s2.empty()){
x = s2.top();
s2.pop();
}else{
if(s1.empty()){
x = -1;
}else{
while(s1.size() > 1){
s2.push(s1.top());
s1.pop();
}
x = s1.top();
s1.pop();
}
}
return x;
}
};
int main(){
int n,key;
char str[10];
while(scanf("%d",&n) != EOF){
queue s;
for(int i = 0;i < n;i++){
scanf("%s",str);
if(!strcmp(str,"PUSH")){
scanf("%d",&key);
s.add(key);
}else if(!strcmp(str,"POP")){
printf("%d\n",s.remove());
}
}
}
system("pause");
}
2.两个队列实现栈
大致思路:其中一个队列作为缓冲区,如进栈时,将元素进入S1和S2中其中有元素的那个队列(另一个缓冲区是一定是空的),如果两个都是空的,选S1或者S2都OK,出栈时,加入S1中有元素,S2为空,那么将S1中前(S1.size()-1)个元素出队列S1,然后加入到S2中,将S1中的队尾的元素出队列,完成了出栈
#include <iostream>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
/* two queue construct a stack */
class stack{
private:
queue<int> s1,s2;
public:
stack(){
while(!s1.empty()){
s1.pop();
}
while(!s2.empty()){
s2.pop();
}
}
~stack(){}
void push(int x){
if(!s1.empty())
s1.push(x);
else if(!s2.empty())
s2.push(x);
else{
s1.push(x);
}
}
int pop(){
int x;
if(!s1.empty()){
while(s1.size() > 1){
s2.push(s1.front());
s1.pop();
}
x = s1.front();
s1.pop();
}else if(!s2.empty()){
while(s2.size() > 1){
s1.push(s2.front());
s2.pop();
}
x = s2.front();
s2.pop();
}else{
x = -1;
}
return x;
}
};
int main(){
stack s;
char t[10];
int key;
while(1){
scanf("%s",t);
if(strcmp(t,"PUSH") == 0){
scanf("%d",&key);
s.push(key);
}else if(strcmp(t,"POP") == 0){
printf("%d\n",s.pop());
}
}
system("pause");
}