LeetBook作业记录:用队列实现栈


题目概述

用两个队列实现栈的基本操作push, top, pop,empty。均摊时间复杂度最好是O(1)


题目地址:https://leetcode-cn.com/leetbook/read/queue-stack/gw7fg/

一、作业思路

一开始,我还想着“用栈实现队列”和“用队列实现栈”应该差不过,思路可以借鉴,于是就顺着pop那个环节倒腾元素去了,结果绕了好久,终于发现还是在push环节把问题解决掉比较好。

因为要保证Last in first out, 而队列只能从头部out,我们在插入数据的时候必须保证last in的数据元素排在队首,也就是我们每次插入都必须保证在队列中逆序存储数据元素。也是因为顺序的重要性,我们每次操作之后都必须保证数据都存在一个队列里,否则顺序会乱。

其实我觉得用队列实现栈要比用栈实现队列难一些:
1)我们总是要保持一个队列为空,其实想到这一点我花了好久,一开始一直在想最后进的元素要存在哪一个队里(捂脸),陷入了栈的僵局。
2)数据需要倒两次,倒入备用的空队列之后,还得倒回来。其实也有想过要不引入一个临时变量吧,但是又怕不符合题目要求。

二、作业记录

1.作业代码

代码如下:

class MyStack {

    Queue<Integer> in = new ArrayDeque<Integer>();
    Queue<Integer> out = new ArrayDeque<Integer>();

    /** Initialize your data structure here. */
    public MyStack() {
    
        in = new ArrayDeque<Integer>();
        out = new ArrayDeque<Integer>(); 
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
    
        if( out.isEmpty() ){
            out.offer(x);
        }else{
            while(! out.isEmpty()){
                in.offer(out.poll());
            }
            out.offer(x);
            while( !in.isEmpty()){
                out.offer(in.poll());
            }
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
       return out.poll();
    }
    
    /** Get the top element. */
    public int top() {
       return out.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return in.isEmpty() && out.isEmpty();

    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

2.作业表现

表现如下:

在这里插入图片描述
内存消耗有些大,是因为Queue的实现方式导致的吗?

把队列的实现方式换成LinkedList,结果稍有改观?:
在这里插入图片描述


复杂度分析

时间复杂度:均摊时间复杂度是O(1),最差的情况就是push全部数据元素进队列,倒腾两遍数据逆排序,时间复杂度是O(n)。其他操作都是O(1)的复杂度。

空间复杂度:数据没有重复存储,我个人认为空间复杂度也是O(1)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不争之德

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值