【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)

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