力扣 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();
    }
};
相关推荐
渡我白衣15 分钟前
深度学习优化算法深入分析:从 SGD 到 LAMB
人工智能·深度学习·算法
2401_8772742417 分钟前
vector、list、deque的差异
数据结构·list
earthzhang202133 分钟前
【1008】计算(a+b)/c的值
c语言·数据结构·c++·算法·青少年编程
dlraba8021 小时前
YOLO 目标检测算法全解析:原理、分类与性能指标
算法·yolo·目标检测
jllllyuz1 小时前
基于K近邻(KNN)算法的高光谱数据分类MATLAB实现
算法·matlab·分类
勇闯逆流河1 小时前
【C++】红黑树详解
开发语言·数据结构·c++
时间醉酒1 小时前
数据结构实战:顺序表全解析 - 从零实现到性能分析
数据结构
Craaaayon2 小时前
【数据结构】二叉树-图解广度优先搜索
java·数据结构·后端·算法·宽度优先
DuHz2 小时前
汽车角雷达波形设计与速度模糊解决方法研究——论文阅读
论文阅读·物联网·算法·汽车·信息与通信·信号处理
学习编程的Kitty2 小时前
算法——位运算
java·前端·算法