Ang Imhr.ca ay narito upang tulungan kang makahanap ng mga sagot sa lahat ng iyong mga katanungan mula sa mga eksperto. Nagbibigay ang aming platform ng seamless na karanasan para sa paghahanap ng eksaktong sagot mula sa isang network ng mga bihasang propesyonal. Tuklasin ang komprehensibong mga solusyon sa iyong mga tanong mula sa mga bihasang propesyonal sa iba't ibang larangan sa aming platform.
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 paggamit ng aming plataporma. Lagi kaming narito upang magbigay ng tumpak at napapanahong mga sagot sa lahat ng iyong mga katanungan. Pinahahalagahan namin ang iyong oras. Mangyaring bumalik anumang oras para sa pinakabagong impormasyon at mga sagot sa iyong mga tanong. Maraming salamat sa pagtiwala sa Imhr.ca. Bumalik muli para sa mas marami pang impormasyon at kasagutan.