代码随想录09| 232.用栈实现队列, 225. 用队列实现栈

232.用栈实现队列

题目链接/文章讲解/视频讲解:链接地址

代码思路:队列是先进先出,栈是先进后出,要用栈来实现队列的功能,可以使用两个栈来实现,一个栈用来输入数据,一个栈用来输出数据。

class MyQueue {
public:
    stack<int> stack_in;
    stack<int> stack_out;
    MyQueue() {

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

    }
    
    int pop() {
        if (stack_out.empty()){
            while (!stack_in.empty()) {
                stack_out.push(stack_in.top());//C++中栈pop()返回的是少了最后一个元素的数组,不是最后一个元素
                stack_in.pop();
            }
        }
        int result = stack_out.top();
        stack_out.pop();
        return result;

    }
    
    int peek() {
        int ans = this->pop();
        stack_out.push(ans);
        return ans;
    }
    
    bool empty() {
        return stack_in.empty() && stack_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. 用队列实现栈

题目链接/文章讲解/视频讲解:链接地址

代码思路:栈是一种先进后出的数据结构,可以使用一个双端队列,封闭掉一个出口来实现。将队列的头部除了最后一个元素都向队列的尾部去添加。

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

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

    }
    
    int pop() {
        //将队列头部的元素(除了最后一个元素外)重新添加到队列尾部

        if (this->empty()) {
            return -1;
        }
        int size = stack.size();
        size--;
        while (size--) {
            stack.push(stack.front());
            stack.pop();//队列是先进先出,pop的是除了第一个元素的数组
        }
        int result = stack.front();
        stack.pop();
        return result;
    }
    
    int top() {
        int ans = this->pop();
        stack.push(ans);
        return ans;

    }
    
    bool empty() {
        return stack.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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值