232. 用栈实现队列 java

使用栈实现队列的下列操作:

  • push(x) -- 将一个元素放入队列的尾部。
  • pop() -- 从队列首部移除元素。
  • peek() -- 返回队列首部的元素。
  • empty() -- 返回队列是否为空。

示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // 返回 1
queue.pop();   // 返回 1
queue.empty(); // 返回 false

说明:

  • 你只能使用标准的栈操作 -- 也就是只有 push to toppeek/pop from topsize, 和 is empty 操作是合法的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
  • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

代码:

多次加入,一次倒出
从上一个例子我们可以看见,桶1中的内容一定是输入顺序的逆序,而桶2中的内容则一定和输入顺序相同。那么我们能不能保证无时无刻,桶1中的元素全部位于桶2之后,从而确保每次从桶2中获得的元素是正确的顺序。而当桶2中没有元素时,只要导入桶1的元素就可以了。

方法是每次添入元素时,仍然直接加入桶1。但是当需要弹出元素时,则从桶2弹出。如果桶2是空的话,那么就把桶1中的内容倒入桶2。这样,下次加入的元素必然全部位于桶2后的所有元素,而桶2中的元素也能保证位输入顺序。图例如下:

class MyQueue {

    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    /** Initialize your data structure here. */
    
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        stack1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */

        //确保了每个元素只会入栈出栈再入栈出栈两次,即进入桶1,弹出桶1,进入桶2,弹出桶2。
    public int pop() {
         if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());//
            }
        }
        return stack2.pop();//若stack2不为空,直接将stack2栈顶元素出栈即可。
    }   
    
    /** Get the front element. */
    public int peek() {
       if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());/。
            }
        }
        return stack2.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
         return stack1.empty() && stack2.empty();//当二者均为空是,队列为空
    }
}

/**
 * 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();
 */

 首先要在队列下申明两个栈

class MyQueue {

    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    /** Initialize your data structure here. */
    
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }
}

 

猜你喜欢

转载自blog.csdn.net/nsjlive/article/details/82595123