【Leetcode栈与队列】225. 用队列实现栈

Leetcode225

1.问题描述

在这里插入图片描述
在这里插入图片描述

2.解决方案

动画模拟!

(1)思路:

在这里插入图片描述

(2)画图解释:

在这里插入图片描述

在这里插入图片描述


(3)代码实现:

版本一:两个队列实现栈
class MyStack {
private:
    queue<int> q1;
    queue<int> q2;
public:
    MyStack() {
    }

    void push(int x) {
        if(q1.empty()== true){
            q2.push(x);
        } else{
            q1.push(x);
        }
    }

    int pop() {
        if(q1.empty()==true){
            while(q2.size()>1){
                q1.push(q2.front());
                q2.pop();
            }
            int t=q2.front();
            q2.pop();
            return t;
        } else{
            while(q1.size()>1){
                q2.push(q1.front());
                q1.pop();
            }
            int t=q1.front();
            q1.pop();
            return t;
        }
    }

    int top() {
        if(q1.empty()==true){
            while(q2.size()>1){
                q1.push(q2.front());
                q2.pop();
            }
            int t=q2.front();
            q1.push(t);
            q2.pop();
            return t;

        } else{
            while(q1.size()>1){
                q2.push(q1.front());
                q1.pop();
            }
            int t=q1.front();
            q2.push(t);
            q1.pop();
            return t;
        }
    }

    bool empty() {
        if(!q1.empty()||!q2.empty()) return false;
        else return true;
    }
};
版本二:一个队列实现栈

1.其实这道题目就是用一个队列就够了,一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
2.此时在去弹出元素就是栈的顺序了。

class MyStack {
public:
    queue<int> que;
    /** Initialize your data structure here. */
    MyStack() {

    }
    /** Push element x onto stack. */
    void push(int x) {
        que.push(x);
    }
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int size = que.size();
        size--;
        while (size--) { // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
            que.push(que.front());
            que.pop();
        }
        int result = que.front(); // 此时弹出的元素顺序就是栈的顺序了
        que.pop();
        return result;
    }

    /** Get the top element. */
    int top() {
        return que.back();
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return que.empty();
    }
};
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值