Ch3-5: implement myqueue with 2 stacks

本文详细介绍了如何通过两个栈实现队列的先进先出(FIFO)特性,同时解释了如何利用其中一个栈作为缓冲区来实现先进后出(LIFO)的特性。通过实例代码演示了如何在不同情况下移动数据以反转顺序,从而优化队列操作的效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

since Stack is LIFO, Queue is FIFO;

in order to implement LIFO, need to have a stack1 to buff the data and back to stack2 for pop. it is just like cooling the hot water with 2 cups, it can reverse the order.

But one thing need to notice. we only reverse the order if we have no water in stack2 for drink. so only in pushing, we directly pour water in stack1. Other cases, we need to check if stack2 is empty so as to reverse hot water in stack1 to 2.

It save time.

#include 
#include 

using namespace std;

template 
class MyQueue{
public:
    MyQueue(){

    }
    ~MyQueue(){

    }
    void push(T val){
        sin.push(val);  //for push, we don't care about sout
    }
    void pop(){
        move(sin, sout);  // for the rest, only move sin to sout
        sout.pop();       // iff sout is empty
    }
    T front(){
        move(sin, sout);
        return sout.top();
    }
    T back(){
        move(sout, sin);
        return sin.top();
    }
    int size(){
        return sin.size()+sout.size();
    }
    bool empty(){
        return sin.empty()&&sout.empty();
    }
    void move(stack &src, stack &dst){
        if(dst.empty()){
            while(!src.empty()){
                dst.push(src.top());
                src.pop();
            }
        }
    }

private:
    stack sin, sout;    
};

int main(){
    MyQueue q;
    for(int i=0; i<10; ++i){
        q.push(i);
    }

    cout<Executing the program....
$demo 
0 9

1 10

10 0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值