栈实现队列

class MyQueue{
        private Stack<Integer> in = new Stack<>();
        private Stack<Integer> out = new Stack<>();
        
        public void push(int x){
            in.push(x);
        }
        
        public int pop(){
            if(out.isEmpty()){
                while(!in.isEmpty()){
                    out.push(in.pop());
                }
            }
            return out.pop();
        }
        
        public int peek(){
            if(out.isEmpty()){
                while(!in.isEmpty()){
                    out.push(in.pop());
                }
            }
            return out.peek();
        }
        
        public boolean empty(){
            return in.isEmpty() && out.isEmpty();
        }
    }

 

posted @ 2020-08-06 14:50  helloworldmybokeyuan  阅读(65)  评论(0编辑  收藏  举报