队列

2022-04-08  本文已影响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();
    }
}
上一篇下一篇

猜你喜欢

热点阅读