用两个栈实现队列 c++ 9度题目号1512

题目:http://ac.jobdu.com/problem.php?pid=1512

思路为用两个栈,一个入队列一个出队列。

对自定义队列MyQueue执行push的时候直接往入队列栈push。

对自定义队列MyQueue执行pop的时候如果出队栈为空而入队栈不为空,就将入队栈中所有元素pop出来push到出队栈中,然后pop一次出队栈。

#include <iostream>

#include <cstdio>
#include <stack>
#define MAXSIZE 100000
using namespace std;
 
class MyQueue{
private:
    stack<int> in, out;
 
public:
    MyQueue() {}
    ~MyQueue() {}
    void push(int key) {
        in.push(key);
    }
    void pop() {
        if (out.empty()) {   //如果出队栈为空 
            if (!in.empty()) {  //如果入队栈不为空 
                while (!in.empty()) {  //当入队栈不为空 
                    out.push(in.top());   //将入队栈的所有数据转移到出队栈中 
                    in.pop();
                }
            }
        }
        if (!out.empty()) {   //如果出队栈不为空 
            cout << out.top() << endl;  //输出 出队栈 
            out.pop();
        }
        else cout << "-1" << endl;
 
    }
    void clear_() {
        while (!in.empty()) in.pop();
        while (!out.empty()) out.pop();
    }
};
 
int main()
{
    MyQueue Q;
    int n;
    while (cin >> n) {
        while (n--) {
            string s;
            int key;
            cin >> s;
            if (s == "PUSH") {
                cin >> key;
                Q.push(key);
            }
            else if (s == "POP") Q.pop();
        }
        Q.clear_();
    }
    return 0;
}

 


 
/**************************************************************
    Problem: 1512
    Language: C++
    Result: Accepted
    Time:620 ms
    Memory:1656 kb
****************************************************************/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值