10-用栈实现队列

2021-08-14  本文已影响0人  weyan

代码:
package 栈;

import java.util.Stack;

/**_232_用栈实现队列
 * url: https://leetcode-cn.com/problems/implement-queue-using-stacks/
 **/
public class _232_用栈实现队列 {
    private Stack<Integer> inStack;
    private Stack<Integer> outStack;
    /** Initialize your data structure here. */
    public _232_用栈实现队列() {
        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() {
        checkOutStack();
        return outStack.pop();
    }
    
    /** Get the front element.队头 */
    public int peek() {
        checkOutStack();
        //返回栈顶元素
        return outStack.peek();
    }
    
    /** Returns whether the queue is empty.是否为空 */
    public boolean empty() {
        return inStack.isEmpty() && outStack.isEmpty();
    }
    
    private void checkOutStack() {
        if (outStack.isEmpty()) {
            while (!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }
        }
    }

}

上一篇 下一篇

猜你喜欢

热点阅读