力扣 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();
    }
};
相关推荐
大二转专业41 分钟前
408算法题leetcode--第24天
考研·算法·leetcode
凭栏落花侧1 小时前
决策树:简单易懂的预测模型
人工智能·算法·决策树·机器学习·信息可视化·数据挖掘·数据分析
Starry_hello world2 小时前
二叉树实现
数据结构·笔记·有问必答
hong_zc2 小时前
算法【Java】—— 二叉树的深搜
java·算法
吱吱鼠叔3 小时前
MATLAB计算与建模常见函数:5.曲线拟合
算法·机器学习·matlab
嵌入式AI的盲4 小时前
数组指针和指针数组
数据结构·算法
reyas6 小时前
B树系列解析
数据结构·b树
Indigo_code6 小时前
【数据结构】【顺序表算法】 删除特定值
数据结构·算法
__AtYou__7 小时前
Golang | Leetcode Golang题解之第448题找到所有数组中消失的数字
leetcode·golang·题解
阿史大杯茶7 小时前
Codeforces Round 976 (Div. 2 ABCDE题)视频讲解
数据结构·c++·算法