![]() |
VOOZH | about |
Given a queue, reverse the elements of the queue using recursion. The task is to reverse the order of the elements in the queue and return the reversed queue.
Standard operations allowed:
Examples :
Input : Q = [5, 24, 9, 6, 8, 4, 1, 8, 3, 6]
Output : Q = [6, 3, 8, 1, 4, 8, 6, 9, 24, 5]
Explanation : Output queue is the reverse of the input queue.
Input : Q = [8, 7, 2, 5, 1]
Output : Q = [1, 5, 2, 7, 8]
Explanation : Output queue is the reverse of the input queue.
Recursive Algorithm :
- The pop element from the queue if the queue has elements otherwise return empty queue.
- Call reverseQueue function for the remaining queue.
- Push the popped element in the resultant reversed queue.
Pseudo Code :
queue reverseFunction(queue)
{
if (queue is empty)
return queue;
else {
data = queue.front()
queue.pop()
queue = reverseFunction(queue);
q.push(data);
return queue;
}
}
Implementation:
100 90 80 58 92 85 45 30 27 56
Complexity analysis: