Any idea as to how to write a simple algorithm to reverse elements in a queue?
Any idea as to how to write a simple algorithm to reverse elements in a queue?
If it's a double linked list, simply swap the Next and Previous pointers and swap the FirstNode and LastNode pointers.
If not, you could create a new list (queue) by picking the first element in the old list, add it first to the new list, then remove it from the old list.
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.
I don't know if this helps, but the standard library provides such a facility...
Code:#include <algorithm> #include <queue> std::queue<int> myqueue; for (int i = 0; i < 10; i++) myqueue.push(i); std::reverse(myqueue.begin(), myqueue.end());
The essence of a queue is that elements are always added to the back of the line & elements are always removed from the front of the line. So if you just remove each element from the queue & add it to a new queue, you end up with a new queue exactly like the original one, in the same order.
But, if you remove each element from the queue and push it onto a stack & continue doing this until the queue is empty & all of the elements are on the stack, and then pop each element off the stack & put it back on the queue, when you finish emptying the stack, your queue will end up with all of its elements in reverse order.