The Dilemma
You have elements `1, 2, 3` in a queue. You need them to be `3, 2, 1`. But the queue only lets you remove `1` first!
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Because Queues are strictly FIFO, you cannot iterate backward. To reverse a Queue, you must leverage the LIFO property of a Stack.
You have elements `1, 2, 3` in a queue. You need them to be `3, 2, 1`. But the queue only lets you remove `1` first!
Dequeue every element and push it onto a Stack. Since `1` is pushed first, it goes to the absolute bottom of the stack. `3` goes to the top.
Pop from the Stack and enqueue back into the Queue. Because `3` is on top, it gets popped and enqueued first! The LIFO nature of the stack naturally reversed the entire set.