代码随想录算法训练营第十天|232.用栈实现队列 、225. 用队列实现栈

代码随想录算法训练营第十天

232.用栈实现队列

题目链接:232.用栈实现队列
使用两个栈一个in_stack,一个out_stack。队列入队就将元素加入in_stack。出队,如果out_stack没有元素就将in_stack里的所有元素加入out_stack,否则不进行这个处理,最后返回out_stack的顶部元素再出栈。

class MyQueue {
public:
    stack<int> in_stack;
    stack<int> out_stack;
    MyQueue() {}

    void push(int x) { in_stack.push(x); }

    int pop() {
        int result;
        if (out_stack.empty()) {
            while (!in_stack.empty()) {
                out_stack.push(in_stack.top());
                in_stack.pop();
            }
        }
        result = out_stack.top();
        out_stack.pop();

        return result;
    }

    int peek() {
        int result;
        result = this->pop();
        out_stack.push(result);
        return result;
    }

    bool empty() {
        if (in_stack.empty() && out_stack.empty())
            return true;
        else
            return false;
    }
};

/**
 * 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 {
public:
    queue<int> stack_que;
    MyStack() {}

    void push(int x) { stack_que.push(x); }

    int pop() {
        int result;
        int count = stack_que.size() - 1;
        while (count--) {
            stack_que.push(stack_que.front());
            stack_que.pop();
        }
        result = stack_que.front();
        stack_que.pop();
        return result;
    }

    int top() { return stack_que.back(); }

    bool empty() { return stack_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();
 */

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值