栈实现队列

基本思路:
1、创建2个栈
stackIn : 放入元素
stackOut: 弹出元素
2、put 方法
直接 push到statckIn 栈就可
3、弹出元素
因为队列的特点是 先进先出的, 而栈是先进后出的,所以栈先进 的元素 被压在了栈低。 所以我们需要先把 栈的元素 弹出放入 另一个stackOut栈中,这样 顺序就会反转,然后 按顺序 一直弹出 stackOut的元素即可。直到stackOut元素被 弹空,然后 再从stackIn中 弹出元素 放到stackOut栈中, 然后 再弹出……
代码如下:

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    /** Initialize your data structure here. */
    MyQueue() {

    }
    /** Push element x to the back of queue. */
    void push(int x) {
        stIn.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        // 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
        if (stOut.empty()) {
            // 从stIn导入数据直到stIn为空
            while(!stIn.empty()) {
                 //先top()取出 stIn的元素,然后 再pop出栈
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        //先top取出stout的元素,然后 再pot出栈
        int result = stOut.top();
        stOut.pop();
        return result;
    }

    /** Get the front element. */
    int peek() {
        int res = this->pop(); // 直接使用已有的pop函数
        stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值