两个栈模拟一个队列和两个队列模拟一个栈(c++实现)


c++实现两个栈模拟队列和两个队列模拟一个栈(剑指offer第七题(P59-P62))

#include <iostream>
#include <stack>
#include <queue>
#include <bits/stdc++.h>

using namespace std;

class Queue {
public:
    void in(const int &k);
    int del();
private:
    stack<int> sta1;
    stack<int> sta2;
};

void Queue::in(const int &k) {
    sta1.push(k);
}
int Queue::del(){
    if (sta2.empty())
    {
        while(!sta1.empty())
        {
            int tem = sta1.top();
            sta2.push(tem);
            sta1.pop();
        }
    }
    if (sta2.empty()) {
        throw runtime_error("no elements to delete!!!");
    }
    int res = sta2.top();
    sta2.pop();
    return res;
}
class Stack{
public:
public:
    void in(const int &k);
    int del();
private:
    queue<int> que1;
    queue<int> que2;
};
void Stack::in(const int &k) {
    que1.push(k);
}
int Stack::del() {
    int res;
    if (que1.empty())
    {
        if (que2.empty())
            throw runtime_error("no elements to delete !!!");
        while(que2.size()>1)
        {
            int tem = que2.front();
            que1.push(tem);
            que2.pop();
        }
        res = que2.front();
        que2.pop();
    }
    else {
        while (que1.size()>1)
        {
            int tem = que1.front();
            que2.push(tem);
            que1.pop();
        }
        res = que1.front();
        que1.pop();
    }
    return res;
}

int main() {
    
    Queue test1;
    test1.in(3);
    test1.in(4);
    test1.del();
    cout << test1.del() << endl;

    Stack test2;
    test2.in(3);
    test2.in(4);
    test2.del();
    cout << test2.del() << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值