栈实现队列

95 阅读1分钟
import java.util.Stack;

public class Stack_To_Queue {
    public static class StackQueue{
        private Stack<Integer> stackPush;
        private Stack<Integer> stackPop;
        public StackQueen(){
            stackPush = new Stack<Integer>();
            stackPop = new Stack<Integer>();
        }
        public void push(int pushInt){
            stackPush.push(pushInt);
        }
        public int poll(){
            if(stackPush.isEmpty() && stackPop.isEmpty()){
                throw new RuntimeException("queen is empty");
            }else if(stackPop.isEmpty()){
                while(!stackPush.isEmpty()){
                    stackPop.push(stackPush.pop());
                }
            }
            return stackPop.pop();
        }
        public int peek(){
            if(stackPush.isEmpty() && stackPop.isEmpty()){
                throw new RuntimeException("queen is empty");
            }else if(stackPop.isEmpty()){
                while(!stackPush.isEmpty()){
                    stackPop.push(stackPush.pop());
                }
            }
            return stackPop.peek();
        }
    }
}