232. 用栈实现队列 + 栈 + 队列

232. 用栈实现队列

LeetCode_232

题目描述

方法一:在push时将原有栈的元素全部出栈然后再将当前元如入栈,最后再将第二个栈的元素入第一个栈

class MyQueue{
    int num;
    Deque<Integer> sta1, sta2;//使用双端队列来模拟栈
    /** Initialize your data structure here. */
    public MyQueue() {
        sta1 = new LinkedList<>();
        sta2 = new LinkedList<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        while(!sta1.isEmpty()){
            sta2.push(sta1.pop());
        }
        sta1.push(x);
        while(!sta2.isEmpty()){
            sta1.push(sta2.pop());
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return sta1.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        return sta1.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return sta1.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();
 */

方法二:两个栈分为入栈和出栈

  1. 在peek或者push的时候,且此时出栈为空,则需要将入栈的所有元素进入出栈中
  2. 在push时只需要将元素进入入栈即可,起到了暂存元素的作用。
class MyQueue{
    int num;
    Deque<Integer> insta, outsta;//使用双端队列来模拟栈
    /** Initialize your data structure here. */
    public MyQueue() {
        insta = new LinkedList<>();
        outsta = new LinkedList<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        insta.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(outsta.isEmpty()){
            while(!insta.isEmpty()){
                 outsta.push(insta.pop());
            }
        }
        
        return outsta.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(outsta.isEmpty()){
            while(!insta.isEmpty()){
                 outsta.push(insta.pop());
            }
        }
        return outsta.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return outsta.isEmpty() && insta.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();
 */
posted @ 2021-03-07 20:54  Garrett_Wale  阅读(74)  评论(0编辑  收藏  举报