力扣 232用栈实现队列

思路:

栈的特性是先进后出,队列是先进先出

因此用两个栈来模拟队列

要实现的功能包括

push 入队列

pop() 出队列

peek获取队列的最上元素

isempty 队列判空

push 正常操作 stin.push(),只要元素入栈就行,stout元素入栈是其他步骤的事

pop()出队列,思路是,当stout为空时,依次弹出stin上方元素知道stin为空,弹出最上面元素包含两步先获取最上面的元素top(),再弹出pop()

peek获取最上元素,复用int result = this->pop()因为这一步的弹出,再把元素放回 stout.push(result) 返回该元素return result

判空,如果两个栈都是空的,那么就空了

复制代码
class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    /** Initialize your data structure here. */
    MyQueue() {

    }
    /** Push element x to the back of queue. */
    void push(int x) {
        stIn.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        // 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
        if (stOut.empty()) {
            // 从stIn导入数据直到stIn为空
            while(!stIn.empty()) {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }

    /** Get the front element. */
    int peek() {
        int res = this->pop(); // 直接使用已有的pop函数
        stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};
相关推荐
梨子串桃子_19 小时前
推荐系统学习笔记 | PyTorch学习笔记
pytorch·笔记·python·学习·算法
夏鹏今天学习了吗19 小时前
【LeetCode热题100(83/100)】最长递增子序列
算法·leetcode·职场和发展
情缘晓梦.19 小时前
C语言指针进阶
java·开发语言·算法
北邮刘老师20 小时前
智能体治理:人工智能时代信息化系统的全新挑战与课题
大数据·人工智能·算法·机器学习·智能体互联网
AlenTech20 小时前
155. 最小栈 - 力扣(LeetCode)
算法·leetcode·职场和发展
mit6.82421 小时前
正反两次扫描|单调性cut
算法
Yzzz-F21 小时前
牛客小白月赛127 E
算法
大锦终21 小时前
递归回溯综合练习
c++·算法·深度优先
Keep__Fighting21 小时前
【神经网络的训练策略选取】
人工智能·深度学习·神经网络·算法
晚风吹长发21 小时前
初步了解Linux中的动静态库及其制作和使用
linux·运维·服务器·数据结构·c++·后端·算法