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.
Problem Explanation
Explanation
To implement a stack using two queues, we can use the following approach:
- Use two queues,
queue1andqueue2, wherequeue1will be the main queue for storing elements in the stack. - For
pushoperation, we always add the new element to the emptyqueue2, then move all elements fromqueue1toqueue2, and finally swap the names ofqueue1andqueue2. - For
popoperation, we simply remove and return the front element fromqueue1. - For
topoperation, we return the front element fromqueue1. - For
emptyoperation, we check ifqueue1is 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.