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

  1. Use two queues
  2. On push, add to empty queue
  3. Move all from other queue

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler