Maligayang pagdating sa Imhr.ca, kung saan maaari kang makakuha ng mga sagot mula sa mga eksperto. Tuklasin ang isang kayamanan ng kaalaman mula sa mga eksperto sa iba't ibang disiplina sa aming komprehensibong Q&A platform. Nagbibigay ang aming platform ng seamless na karanasan para sa paghahanap ng mapagkakatiwalaang sagot mula sa isang malawak na network ng mga propesyonal.
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
Salamat sa pagpili sa aming plataporma. Kami ay nakatuon sa pagbibigay ng pinakamahusay na mga sagot para sa lahat ng iyong mga katanungan. Bisitahin muli kami. Salamat sa pagbisita. Ang aming layunin ay magbigay ng pinaka-tumpak na mga sagot para sa lahat ng iyong pangangailangan sa impormasyon. Bumalik kaagad. Ipinagmamalaki naming magbigay ng sagot dito sa Imhr.ca. Bisitahin muli kami para sa mas marami pang impormasyon.