LeetCode 225 Implement Stack using Queues

思路

只说一下pop和top操作。
(1)对于pop:每次pop的时候:首先将queue中的所有元素依次poll到一个tmp队列中,并用last变量记录最后一个poll出来的元素,用count记录加入tmp队列的次数,用来防止将最后一个需要移除的数据再加进去。最后queue = tmp,返回last即可。
时间复杂度O(n),空间复杂度O(n)
(2)top:与pop操作基本相同,只是不需要用count控制加入tmp队列的次数,因为需要全都加入tmp,最后返回last即可。
时间复杂度O(n),空间复杂度O(n)

代码

class MyStack {

    Queue<Integer> queue;
    /** Initialize your data structure here. */
    public MyStack() {
        queue = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue.offer(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        Queue<Integer> tmp = new LinkedList<>();
        int last = 0, size = queue.size(), count = 0;
        while(!queue.isEmpty()) {
            last = queue.poll();
            if(count < size-1) {
                tmp.offer(last);
                count++;
            }
        }
        queue = tmp;
        return last;
    }
    
    /** Get the top element. */
    public int top() {
        Queue<Integer> tmp = new LinkedList<>();
        int last = 0;
        while(!queue.isEmpty()) {
            last = queue.poll();
            tmp.offer(last);
        }
        queue = tmp;
        return last;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

猜你喜欢

转载自blog.csdn.net/qq_36754149/article/details/88545993