I want to know if the following approach is correct to reverse a queue:
-Dequeue all elements of queue and store them in a array a from index 0 to a.length-1
-Enqueue each element array back to queue but starting at index a.length-1 to 0
is there a better solution? we cud use a stack but its basically the same as using an array like my solution above.
If you know the queue size in advance, your method will work and is slightly more efficient than using a stack because array access is slightly faster than updating the state of a stack.
If you do not know the queue size for any reason, a stack will work fine.
Ensure that your queue is not changing during the reversal operation. If items can be added to the queue while you are dequeueing elements, the size originally measured for the array may no longer be valid. Depending on how you write your code, that could either lead to an exception as you index past the end of the array, or to you leaving some items in the original queue and not reversing them.