美文网首页
3.算法- 用栈实现队列

3.算法- 用栈实现队列

作者: 洧中苇_4187 | 来源:发表于2020-05-19 15:57 被阅读0次

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

    相关文章

      网友评论

          本文标题:3.算法- 用栈实现队列

          本文链接:https://www.haomeiwen.com/subject/azubohtx.html