232. 用栈实现队列

题目:

在这里插入图片描述

思路:

①设计两个栈,一个用来装元素,一个用来弹元素
②每当弹元素的栈为空时,将装元素的栈中的元素弹出并压入弹元素的栈

代码:

class MyQueue {
    Stack<Integer> in_stack;
    Stack<Integer> out_stack;
    /** Initialize your data structure here. */
    public MyQueue() {
        in_stack  = new Stack<Integer>();
        out_stack = new Stack<Integer>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        in_stack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(out_stack.empty()){
            while(!in_stack.empty()){
                out_stack.push(in_stack.pop());
            }  
        }
        return out_stack.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(out_stack.empty()){
            while(!in_stack.empty()){
                out_stack.push(in_stack.pop());
            }
        }
        return out_stack.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        if(in_stack.empty() && out_stack.empty())
            return true;
        return false;
    }
}

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

复杂度分析:

时间复杂度:
①push()
时间复杂度:O(1)
空间复杂度:O(n)
②pop()
时间复杂度:O(1)~O(n);摊还复杂度为O(1)
空间复杂度:O(1)
③empty()
时间复杂度:O(1)
空间复杂度:O(1)
④peak()
时间复杂度:O(1)
空间复杂度:O(1)

知识提要:摊还分析

摊还分析给出了所有操作的平均性能。
摊还分析的核心在于,最坏情况下的操作一旦发生了一次,那么在未来很长一段时间都不会再次发生,这样就会均摊每次操作的代价。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值