用两个栈实现队列

题目描述:

用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。

输入:

每个输入文件包含一个测试样例。
对于每个测试样例,第一行输入一个n(1<=n<=100000),代表队列操作的个数。
接下来的n行,每行输入一个队列操作:
1. PUSH X 向队列中push一个整数x(x>=0)
2. POP 从队列中pop一个数。

输出:

对应每个测试案例,打印所有pop操作中从队列pop中的数字。如果执行pop操作时,队列为空,则打印-1。

样例输入:
3
PUSH 10
POP
POP
样例输出:
10
-1

两个栈in和out,in是输入栈,out是输出栈。PUSH一个数压进in栈,POP一次从out栈弹出一个数,当out栈为空,in栈非空,则一次把in栈的数据全压进out栈,再从out栈弹出一个数。当out栈非空,则直接从out栈弹出一个数即可。两个栈都空,返回-1。
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <stack>
#include <cmath>
#include <queue>
#include <set>
#include <list>
#include <cctype>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define REP(i,j,k) for(int i = j ; i < k ; ++i)
#define MAXV (1000)
#define INF (0x6FFFFFFF)
using namespace std;
 
int main()
{
    //freopen("in.txt","r",stdin);
    stack<int> in;
    stack<int> out;
    int n,x;
    char str[10];
    while(scanf("%d",&n)!=EOF)
    {
        while(n--)
        {
            if(n<0)
                break;
            scanf("%s",str);
            if(strcmp(str,"PUSH")==0)
            {
                scanf("%d",&x);
                in.push(x);
            }
            else if(strcmp(str,"POP")==0)
            {
                if(out.empty()&&in.empty())
                    printf("-1
");
                else if(!out.empty())
                {
                    printf("%d
",out.top());
                    out.pop();
                }
                else
                {
                    while(!in.empty())
                    {
                        out.push(in.top());
                        in.pop();
                    }
                    printf("%d
",out.top());
                    out.pop();
                }
            }
        }
    }
    return 0;
}


 
原文地址:https://www.cnblogs.com/aboutblank/p/3215274.html