232_用栈实现队列

232_用栈实现队列

 

package 队列.queue;

import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/implement-queue-using-stacks/
 * @author Huangyujun
 *
 */
public class _232_用栈实现队列 {
    class MyQueue{
        private Stack<Integer> inStack;
        private Stack<Integer> outStack;

        public MyQueue() {
            inStack = new Stack<>();
            outStack = new Stack<>();
        }
        
        public void push(int x) {
            inStack.push(x);
        }
        
        public int pop() {
            checkOutStack();
            return outStack.pop();
        }
        
        public int peek() {
            checkOutStack();
            return outStack.peek();
        }
        
        private void checkOutStack() {
             while(outStack.isEmpty()) {
                while(!inStack.isEmpty()) {
                    outStack.push(inStack.pop());
                }
            }
        }
        public boolean empty() {
            return inStack.isEmpty() && outStack.isEmpty();
        }
    }
    
}

 

posted @ 2021-12-19 23:33  一乐乐  阅读(27)  评论(0编辑  收藏  举报