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.

  • Time: O(n) Space: O(1)
class MyStack {
    Queue<Integer> q = new LinkedList<>();
    int top = Integer.MIN_VALUE;
    // Push element x onto stack.
    public void push(int x) {
        q.offer(x);
        top = x;
    }
    public void pop() {
        int size = q.size();
        for (int i = 0; i < size - 1; i++) {
            if (i == size - 2) {
                top = q.peek();
            }
            q.offer(q.poll());
        }
        q.poll();
    }
    public int top() {
        return top;
    }
    public boolean empty() {
        return q.isEmpty();
    }
}

results matching ""

    No results matching ""