Skip to content

Latest commit

 

History

History
57 lines (37 loc) · 787 Bytes

File metadata and controls

57 lines (37 loc) · 787 Bytes

Implement Stack using Queues

Problem Link

https://leetcode.com/problems/implement-stack-using-queues/


Pattern

  • Stack
  • Queue
  • Design

Approach

Use a queue and rotate elements on push so the newest element stays at the front.


Time Complexity

O(n) per push, O(1) per pop/top

Space Complexity

O(n)


Java Solution

import java.util.*;
class MyStack {
    private Queue<Integer> queue = new LinkedList<>();

    public void push(int x) {
        queue.offer(x);
        for (int i = 0; i < queue.size() - 1; i++) queue.offer(queue.poll());
    }

    public int pop() {
        return queue.poll();
    }

    public int top() {
        return queue.peek();
    }

    public boolean empty() {
        return queue.isEmpty();
    }
}