package recursivequeue; /** * An implementation of a Queue using a single Stack * The trick is that the recursion utilizes the system stack (!) * * @author levenick Mar 1, 2017 10:10:09 AM */ public class QueueImplementedAsOneStack { Stack theStack; QueueImplementedAsOneStack() { theStack = new Stack(); } boolean iEmpty() { return theStack.isEmpty(); } Integer dequeue() { return theStack.pop(); } void enqueue(int n) { if (theStack.isEmpty()) { // if the stack is empty, simply push, and we are done! theStack.push(n); } else { // otherwise, pop one thing off, put it in your pocket, and *then* enqueue int pocket = theStack.pop(); enqueue(n); theStack.push(pocket); // push back on the thing in your pocket } } }