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

文章介绍了如何使用栈来实现队列以及用队列实现栈的LeetCode题目解法,分别分析了时间复杂度和空间复杂度,并提供了相应的C++代码实现。作者对比了自己的解决方案和参考方案的差异,讨论了不同实现方式对性能的影响。
摘要由CSDN通过智能技术生成

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

第九天是关于kmp的内容,这个放到以后再慢慢探究

232. 用栈实现队列

题目链接:232. 用栈实现队列

思路:

  • 栈和队列对于元素进出的顺序刚好相反,所以通过栈实现队的时候就需要思考怎么实现这种相反的逻辑
  • 对于一个栈来说,后进入的元素先抛出,那如果把栈里元素再插入另一个栈中
  • 假设第一个栈叫栈一,第二个栈叫栈二,那么先进入栈一的元素会在栈底,转移到栈二只有就位于栈顶了
  • 这样就用栈实现了先进先出

这是我的版本的代码,在每次入栈的时候,都整理得到一先插入的元素在栈顶的栈

时间复杂度:O(n),空间复杂度O(n)

代码:

class MyQueue
{
public:
    MyQueue()
    {
    }

    void push(int x)
    {
        while (!simulate_list.empty())
        {
            temp_s.push(simulate_list.top());
            simulate_list.pop();
        }
        temp_s.push(x);
        while (!temp_s.empty())
        {
            simulate_list.push(temp_s.top());
            temp_s.pop();
        }
    }

    int pop()
    {
        int temp = simulate_list.top();
        simulate_list.pop();
        return temp;
    }

    int peek()
    {
        return simulate_list.top();
    }

    bool empty()
    {
        return simulate_list.empty();
    }

    std::stack<int> temp_s;
    std::stack<int> simulate_list;
};

总结:

  • 对比carl哥的代码,在需要出栈的时候才转移栈内元素,感觉他这样的代码,移动栈的次数会更少一些,性能应该会更好
  • 做题体验:哈哈哈哈 > 嘿嘿 > 哎哎 > 嘤嘤
  • 时间:10min
  • 一刷

225. 用队列实现栈

题目链接:225. 用队列实现栈

思路:

  • 和上一道题实现的结果相反,如果惯性思维认为,还需要用两个队列,那就会有问题
  • 因为队列是先进先出的结构,把一个队列转移到另一个队列的时候还是原先的顺序
  • 这里我就用一个队列,插入的时候按照队列本身的方式插入
  • 当要抛出队尾元素的时候,可以将队头元素依次移到队尾,让本身的队尾元素变成对头

时间复杂度:O(n),空间复杂度O(n)

代码:

class MyStack
{
public:
    std::queue<int> simu_stack;

    MyStack()
    {
    }

    void push(int x)
    {
        simu_stack.push(x);
    }

    int pop()
    {
        int size = simu_stack.size();
        for (int i = 0; i < size - 1; ++i)
        {
            simu_stack.push(simu_stack.front());
            simu_stack.pop();
        }
        int res = simu_stack.front();
        simu_stack.pop();
        return res;
    }

    int top()
    {
        int res = this->pop();
        simu_stack.push(res);
        return res;
    }

    bool empty()
    {
        return simu_stack.empty();
    }
};

总结:

  • carl哥这里第一种解法用到了两个队列,其中一个是辅助队列作为备份,这和我上一题的思想其实比较接近
  • 做题体验:哈哈哈哈 > 嘿嘿 > 哎哎 > 嘤嘤
  • 时间:15min
  • 一刷
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值