LeetCode—用棧實現隊列(輔助棧實現)

用棧實現隊列(簡單)

2020年6月3日

題目來源:力扣

在這裏插入圖片描述

解題
用隊列實現棧異曲同工

  • 輔助棧
class MyQueue {
    public Stack<Integer> st;
    /** Initialize your data structure here. */
    public MyQueue() {
        st=new Stack<Integer>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        Stack<Integer> tmp=new Stack<>();
        while(!st.isEmpty()){
            tmp.push(st.pop());
        }
        st.push(x);
        while(!tmp.isEmpty()){
            st.push(tmp.pop());
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return st.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        return st.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return st.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();
 */

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章