剑指 09.两个栈实现一个队列

class CQueue {
public:
    stack<int> st1,st2;  //st1 做插入队列,st2 做删除队列
    CQueue() {
       // while(!st1.empty()) st1.pop();  //初始化,把栈中元素清空(也可以不用)
       // while(!st2.empty()) st2.pop();  //初始化,把栈中元素清空(也可以不用)
    }
    
    void appendTail(int value) {
        st1.push(value);   //有元素来直接插入
    }
    
    int deleteHead()
     {
        if (st1.empty()&&st2.empty())  //如果两个队列都为空,直接返回
        {
            return -1;   
          
        }
        else if(!st2.empty())  如果 st2 不空,就要把 st2 先删空
        {   
                int tp= st2.top();
                st2.pop();
                return tp;
        }
        else if(!st1.empty()&&st2.empty())  //当 st2 空了,就看 st1 空不空
        {
            while(!st1.empty())   //要确保把目前 st1 中的全部 push 到 st2,为了保证先进先出的
            {
                st2.push(st1.top());
                st1.pop();
            }
            int tp2=st2.top();
            st2.pop();
            return tp2;
        }
        return -1;
    }

};
//要保证一堆一堆地删,不然 st2 还有的,st1 的 push 到 st2 中,顺序就问题了

 代码可能不够优雅,有错误望指出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值