Pinadadali ng Imhr.ca ang paghahanap ng mga sagot sa iyong mga katanungan kasama ang isang aktibong komunidad. Tuklasin ang detalyadong mga sagot sa iyong mga tanong mula sa isang malawak na network ng mga eksperto sa aming komprehensibong Q&A platform. Tuklasin ang komprehensibong mga solusyon sa iyong mga tanong mula sa mga bihasang propesyonal sa iba't ibang larangan sa aming platform.

give an algorithm for reversing a queue Q.​

Sagot :

Answer:

Reversing a Queue

Give an algorithm for reversing a queue Q. Only following standard operations are allowed on queue.

enqueue(x) : Add an item x to rear of queue.

dequeue() : Remove an item from front of queue.

empty() : Checks if a queue is empty or not.

Examples:

Input : Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Output : Q = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

Input : [1, 2, 3, 4, 5]

Output : [5, 4, 3, 2, 1]

Approach: For reversing the queue one approach could be to store the elements of the queue in a temporary data structure in a manner such that if we re-insert the elements in the queue they would get inserted in reverse order. So now our task is to choose such data-structure which can serve the purpose. According to the approach, the data-structure should have the property of ‘LIFO’ as the last element to be inserted in the data structure should actually be the first element of the reversed queue. The stack could help in approaching this problem. This will be a two-step process:

Pop the elements from the queue and insert into the stack. (Topmost element of the stack is the last element of the queue)

Pop the elements of the stack to insert back into the queue. (The last element is the first one to be inserted into the queue)

// CPP program to reverse a Queue

#include <bits/stdc++.h>

using namespace std;

// Utility function to print the queue

void Print(queue<int>& Queue)

{

while (!Queue.empty()) {

cout << Queue.front() << " ";

Queue.pop();

}

}

// Function to reverse the queue

void reverseQueue(queue<int>& Queue)

{

stack<int> Stack;

while (!Queue.empty()) {

Stack.push(Queue.front());

Queue.pop();

}

while (!Stack.empty()) {

Queue.push(Stack.top());

Stack.pop();

}

}

// Driver code

int main()

{

queue<int> Queue;

Queue.push(10);

Queue.push(20);

Queue.push(30);

Queue.push(40);

Queue.push(50);

Queue.push(60);

Queue.push(70);

Queue.push(80);

Queue.push(90);

Queue.push(100);

reverseQueue(Queue);

Print(Queue);

}

sa comment section nalang yung iba

Pinahahalagahan namin ang iyong pagbisita. Lagi kaming narito upang mag-alok ng tumpak at maaasahang mga sagot. Bumalik anumang oras. Salamat sa iyong pagbisita. Kami ay nakatuon sa pagbibigay sa iyo ng pinakamahusay na impormasyon na magagamit. Bumalik anumang oras para sa higit pa. Ang Imhr.ca ay nandito upang magbigay ng tamang sagot sa iyong mga katanungan. Bumalik muli para sa higit pang impormasyon.