225. Implement Stack using Queues

Implement the following operations of a stack using queues.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.

我使用单个queue 这样 push,empty是O(1),pop,top是O(n)。一开始使用了ArrayDeque 发现效率比较低 ,使用 LinkedList之后效率高多了。具体的原因可能需要看源码注解了。

class MyStack {
     LinkedList<Integer> queue  = new LinkedList <>();
    /** Initialize your data structure here. */
    public MyStack() {
        
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue.add(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        for(int i = 0 ;i<queue.size()-1;i++)
        {
            queue.add(queue.poll());
        }
        return queue.poll();
    }
    
    /** Get the top element. */
    public int top() {
        for(int i = 0 ;i<queue.size()-1;i++)
        {
           queue.add(queue.poll());
        }
        int result = queue.poll();
        queue.add(result);
        return result ;
    }
    
    /** 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();
 */
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容