3.算法- 用栈实现队列

2020-05-19  本文已影响0人  洧中苇_4187

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();
    }
}

上一篇下一篇

猜你喜欢

热点阅读