3.算法- 用栈实现队列

232.用栈实现队列 https://leetcode-cn.com/problems/implement-queue-using-stacks/

要点:
出栈: 只需关注outStack,如果里面有值,直接出栈,
如果没有,从inStack将值pop到outStack,再从outStack中pop出来,
入栈: 直接入inStack

class MyQueue {

    private Stack<Integer> inStack;
    private Stack<Integer> outStack;

    /** Initialize your data structure here. */
    public MyQueue() {
        inStack = new Stack<>();
        outStack = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        inStack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        shift();
        if (!outStack.isEmpty()) {
            return outStack.pop();
        }
        throw new RuntimeException("队列里没有元素");
    }
    
    public void shift(){
        if(outStack.isEmpty()){
            while(!inStack.isEmpty()){
                outStack.push(inStack.pop());
            }
        }
    }

    /** Get the front element. */
    public int peek() {
      shift();
      if (!outStack.isEmpty()) {
          return outStack.peek();
      }
       
       throw new RuntimeException("队列里没有元素");

    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return inStack.isEmpty() && outStack.isEmpty();
    }
}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容