代码随想录算法训练营第十天|232 用栈实现队列、225 用队列实现栈

栈与队列

  1. 栈(stack):先进后出;队列(queue):先进先出
  2. 栈和队列是STL里面的两个数据结构
  3. 栈不能遍历元素,提供poppush等接口,时间复杂度都为O(1)
  4. 在SGI STL中,如果没有指定底层实现的话,栈和队列默认底层使用的是deque容器

232 用栈实现队列

题目链接:用栈实现队列

思路

首先根据提示代码可以确定:队列只有四个操作:push、pop、peek、empty。针对push操作:队列push依次,栈也push一次。针对pop操作:队列pop一次,pop的是第一个元素;栈pop一次,pop的是最后面的一个元素,因此行为逻辑不统一,需要将栈中元素翻转,翻转后再pop,就和队列pop的元素一样。针对peek操作:队列peek操作,返回的是队首元素,栈何队列相反,因此也要将栈中的元素翻转。针对empty判空操作:只有当两个栈中都没有元素时,队列中才没有元素。

cpp 复制代码
class MyQueue {
public:
    MyQueue() {

    }
    
    void push(int x) {
        stackIn.push(x);
    }
    
    int pop() {
        if(stackOut.empty()){
            while(!stackIn.empty())
            {
                stackOut.push(stackIn.top());
                stackIn.pop();
            }
        }
        int result = stackOut.top();
        stackOut.pop();
        return result;
    }
    
    int peek() {
        int result = this->pop();
        stackOut.push(result);
        return result;
    }
    
    bool empty() {
        if(stackIn.empty() && stackOut.empty()){
            return true;
        }
        return false;

    }
private:
    stack<int> stackIn;
    stack<int> stackOut;
};

225 用队列实现栈

题目链接:用队列实现栈

思路

本题目和上一题目还是有一些区别的。因为队列总是先进先出 ,你无法翻转队列中的元素。所以当栈进行pop操作时,将队列中前面的元素都添加到另一个队列中,然后pop出最后一个元素。

cpp 复制代码
class MyStack {
public:
    MyStack() {

    }
    
    void push(int x) {
        queue1.push(x);
    }
    
    int pop() {
        int size = queue1.size()-1;
        while(size--){
            queue2.push(queue1.front());
            queue1.pop();
        }
        int result = queue1.front();
        queue1.pop();
        queue1 = queue2;
        while(!queue2.empty())
        {
            queue2.pop();
        }
        return result;

    }
    
    int top() {
        int result = this->pop();
        queue1.push(result);
        return result;
    }
    
    bool empty() {
        if(queue1.empty()){
            return true;
        }
        return false;

    }
private:
    queue<int> queue1;
    queue<int> queue2;
};

参考链接:

  1. https://programmercarl.com/0232.用栈实现队列.html#算法公开课
相关推荐
To_OC4 小时前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
金銀銅鐵7 小时前
[Python] 扩展欧几里得算法
python·数学·算法
To_OC10 小时前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode
To_OC1 天前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
05Kevin2 天前
lk每日冒险题--数据结构6.27
算法
To_OC2 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安2 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者2 天前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent