两个栈实现一队列:

两个栈实现一队列:

要加入辅助栈,进行反转操作

栈的顺序为后进先出,而队列的顺序为先进先出。使用两个栈实现队列,一个元素需要经过两个栈才能出队列,在经过第一个栈时元素顺序被反转,经过第二个栈时再次被反转,此时就是先进先出顺序。

class MyQueue {
    Stack<Integer> in=new Stack<>();
    Stack<Integer> out=new Stack<>();

    /** Initialize your data structure here. */
    public MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    //先入栈
    public void push(int x) {
        in.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    //要遵循队列的先入先出,应该让元素从入栈中先进入辅助栈,再出栈
    public int pop() {
        inToOut();
        return out.pop();
    }
    //执行出栈入栈操作
     public void inToOut() {
         if(out.isEmpty()){
           while(!in.isEmpty()){
               out.push(in.pop());
           }
         }
    }
    
    /** Get the front element. */
    public int peek() {
        inToOut();
      return  out.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return in.isEmpty()&&out.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

猜你喜欢

转载自blog.csdn.net/qq_31957639/article/details/83652434