用两个栈(Stack)实现一个队列(Queue)
方法如下:
入队时,将元素压入s1。出队时,判断s2是否为空,如不为空,则直接弹出s2栈顶元素;如为空,则将s1的元素逐个“倒入”s2,把s2栈顶元素弹出。这种方法即简单实现队列。效率较高。
代码:
#include <stdio.h>
#include <stack>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main()
{
int n,pushn;
char a[5];
stack<int> s1;
stack<int> s2;
scanf("%d",&n);
while(n>0)
{
scanf("%s",a);
if(!strcmp(a,"PUSH"))
{
scanf("%d",&pushn);
// printf("this is a push operation!n is %d\n",pushn);
s1.push(pushn);
}else if(!strcmp(a,"POP"))
{
// printf("this is a pop operation!");
if(s2.empty())//如果栈为空
{
// printf("----------s2 is empty\n");
// system("pause");
if(s1.empty()) printf("-1\n");
else{
int k=s1.size();
int popn;
// printf("----------s1 is not empty,s1 size is %d\n",k);
// system("pause");
while(k>0)
{
s2.push(s1.top());
s1.pop();
k--;
}
printf("%d\n",s2.top());
s2.pop();
}
}else{//s2栈不为空
printf("%d\n",s2.top());
s2.pop();
}
}
n--;
}
// system("pause");
return 0;
}