C++ 用两个栈实现一个队列 使用Stack容器

#include <iostream>
#include <algorithm>
#include <stack>

using namespace std;

class MyQueue
{
private:
    stack<int> s1;
    stack<int> s2;
public:
    MyQueue(/* args */);
    ~MyQueue();

    void push_back(int);
    void pop_front();
    int fornt();
    int back();
    bool isempty();
    int size();
};

MyQueue::MyQueue(/* args */)
{
}

MyQueue::~MyQueue()
{
}

void MyQueue::push_back(int elem){
    s1.push(elem);
}

void MyQueue::pop_front(){
    for (int i = s1.size() - 1; i > 0; i--){
        s2.push(s1.top());
        s1.pop();
    }
    s1.pop();
    for (int i = s2.size(); i > 0; i--)
    {
        s1.push(s2.top());
        s2.pop();
    }
}

int MyQueue::fornt(){
     for (int i = s1.size() - 1; i > 0; i--){
        s2.push(s1.top());
        s1.pop();
    }
    int tmp = s1.top();
    for (int i = s2.size(); i > 0; i--)
    {
        s1.push(s2.top());
        s2.pop();
    }
    return tmp;
}

int MyQueue::back(){
    return s1.top();
}


bool MyQueue::isempty(){
    if (s1.empty())
    {
        return true;
    }
    return false;
}

int MyQueue::size(){
    return s1.size();
}


void test(){
    MyQueue Q;
    Q.push_back(12);
    Q.push_back(20);
    Q.push_back(14);
    Q.push_back(8);
    Q.push_back(21);
    Q.push_back(3);
    cout<<Q.back()<<endl;
    cout<<Q.fornt()<<endl;
    cout<<Q.size()<<endl;
    cout<<Q.isempty()<<endl;
    int sizeof_MyQueue = Q.size();
    for (int i = 0; i < sizeof_MyQueue; i++) // 如果直接写成 i < Q.size() 则不对,因为Q的大小随着数据的删除一直在变化
    {
        Q.pop_front();
    }
    cout<<Q.size()<<endl;
    cout<<Q.isempty()<<endl;

    
}


int main(void){
    test();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值