Data Structures · QUEUE

Exercise: Reverse First K Elements of a Queue

Given a queue of integers and a number K, reverse the first K elements while keeping the order of the rest.

🚶 The queue queue<int>

← front (dequeue only here)rear (enqueue only here) →
being processed first K (to be reversed) remaining N−K (order kept) FIFO: first-in-first-out — out at the front, in at the rear → a queue never changes order

📚 The helper stack stack<int>

↑ top
push / pop happen here
LIFO last-in-first-out
→ the order comes out reversed

📤 Result (cout output) first K reversed, the rest unchanged

output:

💬 Current step

💻 The C++ program (STL stack + queue)

Yellow = current line. The slide’s Goal: solve it with the STL stack and queue and watch the stack reverse order while the queue keeps it.

🎯 The three steps (Goal & Hints)

1Use stack<int> to reverse the first K elements (LIFO).
2Pop them back into the queue — now reversed, sitting at the rear.
3Rotate the remaining N−K elements so their order is kept (FIFO).
Goal: use the STL stack + queue and see for yourself that a stack reverses order while a queue preserves it.
Why does it work? The first K go through the stack and come out reversed; the remaining elements are simply moved from front to rear N−K times, so their relative order is untouched.
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result