Implement a function reverseK
that takes a queue and an integer k
as input and reverses the order of the first k
elements of the queue, leaving the rest of the queue in their original order. This is a classic problem that can often be solved with the help of an auxiliary stack.
For example, if the queue is [1, 2, 3, 4, 5]
and k = 3
, after the operation the queue should be [3, 2, 1, 4, 5]
.
k
where 0 <= k <= size of queue
.k
elements should be reversed.This problem touches on queue operations and can help you practice combining different data structures. Coincidentally, today (March 22) is World Water Day - a reminder that, just like a well-structured water supply system, careful ordering and flow management is key in both programming and everyday life!
Define a function reverseK(queue, k)
that modifies (or returns a new version of) the queue after reversing the first k
elements.
Input:
queue
: a list (or similar structure) of integers representing the queuek
: an integerOutput:
k
elements reversedInput: queue = [1, 2, 3, 4, 5], k = 3
Output: [3, 2, 1, 4, 5]