Lintcode 40 用棧實現隊列

40. 用棧實現隊列

中文English

正如標題所述,你需要使用兩個棧來實現隊列的一些操作。

隊列應支持push(element),pop() 和 top(),其中pop是彈出隊列中的第一個(最前面的)元素。

pop和top方法都應該返回第一個元素的值。

樣例

例1:

輸入:
    push(1)
    pop()    
    push(2)
    push(3)
    top()    
    pop()     
輸出:
    1
    2
    2

例2:

輸入:
    push(1)
    push(2)
    push(2)
    push(3)
    push(4)
    push(5)
    push(6)
    push(7)
    push(1)
輸出:
[]

挑戰

僅使用兩個棧來實現它,不使用任何其他數據結構,push,pop 和 top的複雜度都應該是均攤O(1)的

注意事項

假設調用pop()函數的時候,隊列非空

public class MyQueue {
    Stack<Integer> st = new Stack<>();
    Stack<Integer> stHelp = new Stack<>();
    public MyQueue() {
        // do intialization if necessary
    }

    /*
     * @param element: An integer
     * @return: nothing
     */
    public void push(int element) {
        // write your code here
        st.push(element);
    }

    /*
     * @return: An integer
     */
    public int pop() {
        // write your code here
        while (!st.isEmpty()){
            stHelp.push(st.pop());
        } 
        int temp = stHelp.pop();
        while(!stHelp.isEmpty()){
            st.push(stHelp.pop());
        }
        return temp;
    }

    /*
     * @return: An integer
     */
    public int top() {
        // write your code here
        while (!st.isEmpty()){
            stHelp.push(st.pop());
        } 
        int temp = stHelp.peek();
        while(!stHelp.isEmpty()){
            st.push(stHelp.pop());
        }
        return temp;
    }
}

 

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