Simple O(n) peek, and pop, O(1) push, empty, using queue as circular buffer


  • 0
    J
    class MyStack {
    Queue<Integer> q = new ArrayDeque<>();
    
    // Push element x onto stack.
    public void push(int x) {
        q.offer(x);
    }
    
    // Removes the element on top of the stack.
    public void pop() {
        for(int i=1; i<=q.size(); i++){
            if(i < q.size()) q.offer(q.poll());
            else q.poll();
        }
    }
    
    // Get the top element.
    public int top() {
        int v = -1;
        for(int i=1; i<=q.size(); i++){
            if(i == q.size()) v = q.peek();
            q.offer(q.poll());
        }
        return v;
    }
    
    // Return whether the stack is empty.
    public boolean empty() {
        return q.isEmpty();
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.