力扣 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();
    }
};
相关推荐
十八岁讨厌编程9 分钟前
【算法训练营 · 补充】LeetCode Hot100(下)
算法·leetcode·职场和发展
一路往蓝-Anbo16 分钟前
C语言从句柄到对象 (三) —— 抛弃 Malloc:静态对象池与索引句柄的终极形态
c语言·开发语言·数据结构·stm32·单片机·算法
fantasy_arch1 小时前
SVT-AV1 B帧决策和mini-GOP决策分析
算法·av1
声声codeGrandMaster1 小时前
逻辑回归-泰坦尼克号
算法·机器学习·逻辑回归
集芯微电科技有限公司1 小时前
PC1001超高频率(50HMZ)单通单低侧GaN FET驱动器支持正负相位配置
数据结构·人工智能·单片机·嵌入式硬件·神经网络·生成对抗网络·fpga开发
一路往蓝-Anbo1 小时前
C语言从句柄到对象 (二) —— 极致的封装:不透明指针与 SDK 级设计
c语言·开发语言·数据结构·stm32·单片机·嵌入式硬件
上天_去_做颗惺星 EVE_BLUE1 小时前
C++学习:学生成绩管理系统
c语言·开发语言·数据结构·c++·学习
mu_guang_1 小时前
算法图解2-选择排序
数据结构·算法·排序算法
xiaowu0802 小时前
IEnumerable、IEnumerator接口与yield return关键字的相关知识
java·开发语言·算法