Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

//Reverse the first k elements of a queue using an auxiliary stack. Leave the //

ID: 3729616 • Letter: #

Question


//Reverse the first k elements of a queue using an auxiliary stack. Leave the
//rest of the queue the same. Update the original queue.
#include <queue>
#include <stack>
#include <vector>
using namespace std;
void reverseKElementsQueue(queue<int> &q, int k) {
// Code goes here
}
vector<int> stackWrapper(vector<int> v, int k) {
queue<int> q;
for (auto el : v) {
q.push(el);
}
reverseKElementsQueue(q, k);
vector<int> updated = {};
while(!q.empty()) {
updated.push_back(q.front());
q.pop();
}
return updated;
}

Explanation / Answer

please find below the code for reversal of first K elements and no change in rest

void reverseKElementsQueue(queue<int>& Q,int k)

{

stack<int> Stk;

//check if queue is empty or overflow

if (Q.empty() == true || k > Q.size())

return;

if (k <= 0)

return;

// Push the first K elements

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

Stk.push(Q.front());

Q.pop();

}

//Enqueue the contents of Stk at end

while (!Stk.empty()) {

Q.push(Stk.top());

Stk.pop();

}

//Remove the remaining

for (int i = 0; i < Q.size() - k; i++) {

Q.push(Q.front());

Q.pop();

}

}