Learn-dsa..in 30 days!



























CC-10 : Reverse order of all elements of Queue.

Description:

Given a Queue, reverse all nodes of the same.

Test cases and expected outputs:

Input Parameters Expected outputs
Queue queue=new Queue();
queue.addByPriority(99);
queue.addByPriority(14);
queue.addByPriority(77);
queue.addByPriority(34);
queue.addByPriority(21);
queue.addByPriority(82);
queue.queueReverse(queue);
Queue nodes: 14 <- 21 <- 34 <- 77 <- 99
After reversal:
Queue nodes: 99 <- 77 <-34 <- 21 <- 14

Pseudocode:

Initialize a new Stack.
Remove nodes one by one from input Queue and add the same to the Stack.
Remove nodes one by one from the Stack and add to Queue.
Now we have Queue with all nodes reversed.

Code:

public Queue<Integer> 
	queueReverse(Queue<Integer> queue){
	
	Stack<Integer> stack=new Stack<Integer>();
	while (queue.size() !=0) {
		stack.push(queue.remove());
	}
	while (stack.size()!=0) {
		queue.add(stack.pop());
	}
	return queue;
}   

Click here to download and run code and test cases !