Reverse First K elements of Queue

Tags : queue, geeksforgeeks, cpp, easy

Given an integer K and a queue of integers, we need to reverse the order of the first K elements of the queue, leaving the other elements in the same relative order.

Only following standard operations are allowed on queue.

Note: The above operations represent the general processings. In-built functions of the respective languages can be used to solve the problem.

Your Task: Complete the provided function modifyQueue that takes queue and k as parameters and returns a modified queue. The printing is done automatically by the driver code.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

Examples #

Example 1:

Input:
4 4
4 3 2 1

Output: 
1 2 3 4

Explanation: 
After reversing the given
input from the 4th position the resultant
output will be 1 2 3 4.

Example 2:

Input:
5 3
1 2 3 4 5

Output: 
3 2 1 4 5

Explanation: 
After reversing the given
input from the 3rd position the resultant
output will be 3 2 1 4 5.

Constraints #

Solutions #

// Function to reverse first k elements of a queue.
queue<int> modifyQueue(queue<int> q, int k) {
    // add code here.
    stack<int> s;
    queue<int> res;
    while(k--) { s.push(q.front()); q.pop(); }
    while(!s.empty()) { res.push(s.top()); s.pop(); }
    while(!q.empty()) { res.push(q.front()); q.pop(); }
    return res;
}