【Leetcode】225. Implement Stack using Queues

题目地址:

https://leetcode.com/problems/implement-stack-using-queues/
用队列实现栈。思路是,push的时候就入队,并将队头的 n 1 n-1 个元素全offer到队尾;peek或者pop的时候直接poll队头。代码如下:

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

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

时间复杂度:peek或pop: O ( 1 ) O(1) ,push: O ( n ) O(n)

发布了86 篇原创文章 · 获赞 0 · 访问量 1213

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/104003358