leetcode-master/problems/0225.用队列实现栈.md

1.7 KiB
Raw Blame History

题目地址

https://leetcode-cn.com/problems/implement-stack-using-queues/

思路

有的同学可能疑惑这种题目有什么实际工程意义,其实很多算法题目主要是对知识点的考察和教学意义远大于其工程实践的意义,所以面试题也是这样!

用栈实现队列, 和用队列实现栈的思路还是不一样的,这取决于这两个数据结构的性质

建议大家题目编号: 225 和 232 一起做来做

详细如代码注释所示

C++代码

class MyStack {
public:
    queue<int> que1;
    queue<int> que2; // 辅助队列
    /** Initialize your data structure here. */
    MyStack() {

    }

    /** Push element x onto stack. */
    void push(int x) {
        que1.push(x);
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int size = que1.size();
        size--;
        while (size--) { // 将que1 导入que2但要留下最后一个元素
            que2.push(que1.front());
            que1.pop();
        }

        int result = que1.front(); // 留下的最后一个元素就是我们要返回的值
        que1.pop();
        que1 = que2; // 再将que2赋值给que1
        while(!que2.empty()) { // 清空que2
            que2.pop();
        }
        return result;
    }

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

    /** Returns whether the stack is empty. */
    bool empty() {
        return que1.empty();
    }
};

更多算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。