力扣 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();
    }
};
相关推荐
iAkuya13 小时前
(leetcode)力扣100 36二叉树的中序遍历(迭代递归)
算法·leetcode·职场和发展
wangwangmoon_light13 小时前
1.1 LeetCode总结(线性表)_枚举技巧
算法·leetcode·哈希算法
码农小韩13 小时前
基于Linux的C++学习——动态数组容器vector
linux·c语言·开发语言·数据结构·c++·单片机·学习
mit6.82414 小时前
几何|阻碍链
算法
有一个好名字14 小时前
力扣-小行星碰撞
算法·leetcode·职场和发展
MM_MS14 小时前
Halcon图像锐化和图像增强、窗口的相关算子
大数据·图像处理·人工智能·opencv·算法·计算机视觉·视觉检测
lamentropetion14 小时前
E - Equal Tree Sums CF1656E
算法
代码游侠14 小时前
应用——智能配电箱监控系统
linux·服务器·数据库·笔记·算法·sqlite
Xの哲學14 小时前
Linux Platform驱动深度剖析: 从设计思想到实战解析
linux·服务器·网络·算法·边缘计算
逑之14 小时前
C语言笔记11:字符函数和字符串函数
c语言·笔记·算法