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 !
Below fully running code can be copied and run on Eclipse or other Java IDEs. Refer the classname in code below. If the class name below is "A", save the code below to a file named A.java before running it.
Be sure to try your own test cases to enhance your understanding !
You can also tweak the code to optimize or add enhancements and custom features.
import java.util.*;
import java.util.Queue;
import java.util.Stack;
public class QueueReverse {
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;
}
public static void printQueue(Queue<Integer> queue) throws Exception {
if (queue.size() == 0) { System.out.println("Queue empty"); return; }
System.out.println();
System.out.println("*********************************************************************");
System.out.print("Queue nodes: ");
Iterator itr=queue.iterator();
while (itr.hasNext()) {
System.out.print(itr.next());
System.out.print(" <- ");
}
System.out.println();
System.out.println("*********************************************************************");
System.out.println();
Thread.sleep(2000);
return;
}
public static void main(String[] args) {
/* Test cases given below: */
try {
Queue<Integer> queue=new LinkedList<Integer>();
System.out.print("Add to Queue: ");
queue.add(9);
queue.add(14);
queue.add(17);
queue.add(34);
queue.add(21);
queue.add(28);
printQueue(queue);
QueueReverse queueReverse=new QueueReverse();
System.out.println("Reverse: ");
queue=queueReverse.queueReverse(queue);
printQueue(queue);
}catch (Exception exception) {
System.out.print("Exception: "+ exception);
}
}
}