两个栈实现队列

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
思路:用两个栈来等效成队列。将一个栈元素弹出,是将该栈中的元素全部反序,模拟队列的头部删除元素。插入元素直接在栈的后边进行插入。

class CQueue {
private:
stack<int> out;//队列的头部
stack<int>ins;//队列的尾部
public:
    CQueue() {
    //清空栈中的元素
        while(!out.empty())
        {
            out.pop();
        }
        while(!ins.empty())
        {
            ins.pop();
        }
    }
    
    void appendTail(int value) {
        ins.push(value);
    }
    
    int deleteHead() {
        if(!out.empty())//直接删除元素 {
            int del= out.top();
            out.pop();
            return del;
        }
        else{
            while(!ins.empty())//将栈中元素反序,出入另一个栈中进行模拟队列头部元素删除
            {
                out.push(ins.top());
                ins.pop();
            }
            if(out.empty()) return-1;
            else
            {
                int del= out.top();
                out.pop();
                return del;
            }
        }
    }
};

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue* obj = new CQueue();
 * obj->appendTail(value);
 * int param_2 = obj->deleteHead();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值