LeetCode 225: Implement Stack using Queues Solution

Master LeetCode problem 225 (Implement Stack using Queues), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

225. Implement Stack using Queues

Problem Explanation

Explanation

To implement a stack using two queues, we can use the following approach:

  • Use two queues, queue1 and queue2, where queue1 will be the main queue for storing elements in the stack.
  • For push operation, we always add the new element to the empty queue2, then move all elements from queue1 to queue2, and finally swap the names of queue1 and queue2.
  • For pop operation, we simply remove and return the front element from queue1.
  • For top operation, we return the front element from queue1.
  • For empty operation, we check if queue1 is empty.

This approach allows us to maintain the stack properties using two queues efficiently.

Time Complexity:

  • push: O(n) where n is the number of elements in the stack.
  • pop, top, empty: O(1)

Space Complexity:

  • O(n) where n is the number of elements in the stack.

Solution Code

import java.util.LinkedList;
import java.util.Queue;

class MyStack {
    private Queue<Integer> queue1;
    private Queue<Integer> queue2;

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        queue2.offer(x);
        while (!queue1.isEmpty()) {
            queue2.offer(queue1.poll());
        }
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
    }

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

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

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

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 225 (Implement Stack using Queues)?

This page provides optimized solutions for LeetCode problem 225 (Implement Stack using Queues) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 225 (Implement Stack using Queues)?

The time complexity for LeetCode 225 (Implement Stack using Queues) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 225 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 225 in Java, C++, or Python.

Back to LeetCode Solutions