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

你可能感兴趣的:(225. Implement Stack using Queues)