Write the following method in java:
public static void reverse(Queue<Integer> q)
which uses a stack to reverse the order of all the items in q.
The idea here is as to reverse the queue we need a data structure that temporarily stores the queue in reverse order. And as we know we can achieve this with a stack as that is LIFO. So, we one by one push all the elements in the stack till queue is not empty. The last element in the queue will be at the top of the stack. Then we again pop the elements from the stack and store it in the queue. steps :-
1. queue - [2,3,5,4]
2. stack - [4,5,3,2] (Pop the elements from the queue and insert into the stack. 4 is at the top)
queue - []
3. queue - [4,5,3,2] (Pop the elements of the stack to insert back into the queue.)
function
public static void reverse(Queue<Integer> q)
{
Stack<Integer> stack =
new
Stack<>();
while
(!q.isEmpty()) {
stack.add(q.peek());
q.remove();
}
while
(!stack.isEmpty()) {
q.add(stack.peek());
stack.pop();
}
}
Get Answers For Free
Most questions answered within 1 hours.