Stack Using Queues in Java: Explanation & Practice
Implement a stack using only queues
Problem summary
Create a Stack class that internally uses only Queue operations.
Starter code
import java.util.*;
public class Main {
public static void main(String[] args) {
// Implement stack using queues
// push(1), push(2), push(3)
// pop() should return 3
// Print: Popped: <value>
}
}Expected output and test cases
- LIFO behavior
Popped: 3
- After more pushes
Popped: 5
- Single element
Popped: 1
Hints
- Use two queues
- On push, add to empty queue
- Move all from other queue
Related Collections exercises
- Practice First Unique Element in Java
- Practice Merge K Sorted Lists in Java
- Practice Group Anagrams in Java
Practice all Collections exercises · Run this idea in the Java compiler