Question:
How to reverse the first K elements of queue using C++

Summary

Consider an aspect:

Give an integer K with a queue of integers, and complete the task of reversing the order of the first element of the queue, leaving the other elements in the same relative order. 


Let’s assume:

Method- modifyQueue

Input elements- int n = q.size()


Solution


// User function Template for C++


class Solution

{

    public:

    

    // Function to reverse first k elements of a queue.

    queue<int> modifyQueue(queue<int> q, int k) {

        // add code here.

        int n = q.size();

        

        stack<int>st;

        for(int i=0;i<=k-1;i++){

            st.push(q.front());

            q.pop();

        }

        for(int i=0;i<k;i++){

            q.push(st.top());

            st.pop();

        }

        for(int i=0;i<n-k;i++){

            q.push(q.front());

            q.pop();

        }

        

        return q;

    }

};


Suggested blogs:

>Find the number of pairs of elements whose sum is equal to K using C++

>How to check whether string is palindrome or not using C++

>How to determine the smallest possible size of a vertex cover using C++

>Build an Electron application from scratch

>Building Web API using ASP.NET (C#)

>Built Web API using ASP.NET (C#)


Nisha Patel

Nisha Patel

Submit
0 Answers