[LeetCode]225. Implement Stack using Queues

[LeetCode]225. Implement Stack using Queues

题目描述

这里写图片描述

思路

用队列处理时使用一个变量保存栈顶元素,可以稍微加快速度
另一种方法,在push时直接改变输入顺序

代码

#include <iostream>
#include <queue>

using namespace std;

class MyStack {
public:
    MyStack() {
        top_value = 0;
    };

    void push(int x) {
        top_value = x;
        q.push(x);
    }

    int pop() {
        int res = 0;
        if (q.size()){
            res = top_value;
            queue<int> temp;
            while (q.size() > 1) {
                temp.push(q.front());
                if (q.size() == 2)
                    top_value = q.front();
                q.pop();
            }
            q.pop();
            while (temp.size()) {
                q.push(temp.front());
                temp.pop();
            }
        }
        return res;
    }

    int top() {
        return top_value;
    }

    bool empty() {
        return q.empty();
    }
private:
    queue<int> q;
    int top_value;
};
/*
方法二
class MyStack {
    queue<int> q;
public:
    void push(int x) {
        q.push(x);
        for (int i=1; i<q.size(); i++) {
            q.push(q.front());
            q.pop();
        }
    }

    int pop() {
        int res = q.front();
        q.pop();
        return res;
    }

    int top() {
        return q.front();
    }

    bool empty() {
        return q.empty();
    }
};
*/

int main() {
    MyStack obj;
    int x = 1;
    obj.push(1);
    obj.push(2);
    int param_2 = obj.pop();
    int param_3 = obj.top();
    bool param_4 = obj.empty();

    cout << param_2 << " " << param_3 << " " << param_4 << endl;

    system("pause");

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值