代码随想录【Day 10】232.用栈实现队列、225. 用队列实现栈

232.用栈实现队列

题目链接:232.用栈实现队列

卡尔文解

解题思路重点:

使用栈来模式队列的行为,如果仅仅用一个栈,是一定不行的,所以需要两个栈一个输入栈,一个输出栈,这里要注意输入栈和输出栈的关系

代码实现:

class MyQueue {
private:
    std::stack<int> stk_in;
    std::stack<int> stk_out;

public:
    MyQueue() {

    }
    
    void push(int x) {

        stk_in.push( x );
    }
    
    
    int pop() {

        int ret;

        // Always popping elements from out stack unless it is empty.
        // Then will push more elements from in stack.
        if ( stk_out.empty() ){

            while ( !stk_in.empty() ){

                stk_out.push( stk_in.top() );
                stk_in.pop();
            }
        }

        ret = stk_out.top();
        stk_out.pop();
        return ret;
    }
    
    int peek() {
        
        // Why below code doesn't work?
        //return( stk_out.top() );

        int ret = this->pop();
        stk_out.push( ret );
        return ( ret );

    }
    
    bool empty() {

        return ( stk_in.empty() && stk_out.empty());
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

225. 用队列实现栈

题目链接:225.用队列实现栈

卡尔文解

解题思路及注意事项:

一个队列在模拟栈弹出元素的时候: 只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。

代码实现:

class MyStack {
private:
    queue<int> _que;
public:
    MyStack() {

    }
    
    void push(int x) {

        _que.push( x );

    }
    
    int pop() {

        int size = _que.size();
        size--;

        while ( size -- ){
            _que.push( _que.front() );
            _que.pop();
        }

        int ret = _que.front();
        _que.pop();
        return ret;
    }
    
    int top() {
        return _que.back();
    }
    
    bool empty() {
        return( _que.empty() );
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值