answersLogoWhite

0

There are many ways to reverse the order of the elements in a queue. Provided that you have access to the implementation of the queue, it is of course easy to read the elements from the tail end rather than the front end, thus reversing the elements.

However, considering the queue as a black box, and assuming the queue only allows for its characteristic operations (removal of head element, addition to tail), the best method to reverse the elements in a queue to engage a stack.

You'd remove the elements from the queue (always reading the head of the queue), and push each element onto the stack. When the queue is empty, you reverse that process: pop each element from the stack until it is empty, and add each element in this order to the end of the queue.

Your queue will have the exact same elements as in the beginning, but in reverse order.

The exact implementation of this in C, or in any other programming language, is trivial, but the exact source code depends on the implementation of queue and stack containers.

Following is pseudocode:

Queue<Item> reverse (Queue<Item> queue) {

Stack<Item> stack;

Item item;

while (queue.remove(&item)) {

stack.push(item);

}

while(stack.pop(&item)) {

queue.add(item);

}

return queue;

}

User Avatar

Wiki User

12y ago

What else can I help you with?