队列

作者: 奋斗的韭菜汪 | 来源:发表于2022-04-08 10:45 被阅读0次

    用栈实现队列
    click here for leetcode detail

    class MyQueue {
        Stack<Integer> firstStack;
        Stack<Integer> secondStack;
    
        public MyQueue() {
            firstStack = new Stack();
            secondStack = new Stack();
        }
        
        public void push(int x) {
            firstStack.push(x);
        }
        
        public int pop() {
            if(empty()){
                return -1;
            }
            //这里需要注意,两个栈同时利用,保证每组连续的push一次性进secondStack,
            //secondeStack为空才进行下一组的firstSatck到secondStack
            if(secondStack.empty()){
                while(!firstStack.empty()){
                    secondStack.push(firstStack.pop());
                }
            }
            return secondStack.pop();
        }
        
        public int peek() {
            if(empty()){
                return -1;
            }
            if(secondStack.empty()){
                while(!firstStack.empty()){
                    secondStack.push(firstStack.pop());
                }
            }
            return secondStack.peek();
        }
        
        public boolean empty() {
            return firstStack.empty() && secondStack.empty();
        }
    }
    

    相关文章

      网友评论

          本文标题:队列

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