【Lintcode】494. Implement Stack by Two Queues

題目地址:

https://www.lintcode.com/problem/implement-stack-by-two-queues/description

用兩個隊列來實現棧。

開兩個隊列q1q_1q2q_2,其中q2q_2作輔助用。push的時候直接向q1q_1裏添加即可。pop和top的時候,要先將q1q_1中除了最後一個元素以外的元素都poll出來並加入q2q_2,然後取出q1q_1僅剩的那個元素,再將兩個隊列引用交換。如果是pop的話,交換前要將q1q_1的那個元素也poll出來,如果是top的話,交換前要將q1q_1那個元素進q2q_2。代碼如下:

import java.util.ArrayDeque;
import java.util.Queue;

public class Stack {
    
    Queue<Integer> q1 = new ArrayDeque<>(), q2 = new ArrayDeque<>();
    
    /*
     * @param x: An integer
     * @return: nothing
     */
    public void push(int x) {
        // write your code here
        q1.offer(x);
    }
    
    /*
     * @return: nothing
     */
    public void pop() {
        // write your code here
        while (q1.size() > 1) {
            q2.offer(q1.poll());
        }
        
        q1.poll();
        Queue<Integer> tmp = q1;
        q1 = q2;
        q2 = tmp;
    }
    
    /*
     * @return: An integer
     */
    public int top() {
        // write your code here
        while (q1.size() > 1) {
            q2.offer(q1.poll());
        }
    
        int res = q1.peek();
        q2.offer(q1.poll());
        
        Queue<Integer> tmp = q1;
        q1 = q2;
        q2 = tmp;
        
        return res;
    }
    
    /*
     * @return: True if the stack is empty
     */
    public boolean isEmpty() {
        // write your code here
        return q1.isEmpty();
    }
}

push時間複雜度O(1)O(1),pop和top時間複雜度O(n)O(n)nn爲已經在隊列裏的元素個數。空間O(n)O(n)

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