Question
The file QueueTest.java contains a printQueue method that takes an object of type QueueADT and prints its contents, restoring the queue before it returns. It
The file QueueTest.java contains a printQueue method that takes an object of type QueueADT and prints its contents, restoring the queue before it returns. It uses a temporary queue that actually holds the same information as the original queue.
If you know the number of elements in the queue, you can write a printQueue method that prints the queue and restores it to its original form without using an auxiliary data structure (stack, queue, etc.). Think about how, then do it! That is, modify the printQueue method in QueueTest so that it behaves exactly as it does now but does not require an auxiliary data structure.
Note that this code uses a LinkedQueue implementation for the QueueADT (see previous exercises), but you could substitute an ArrayQueue if you like.
// ****************************************************************
// QueueTest.java
//
// A simple driver to manipulate a queue.
//
// ****************************************************************
public class QueueTest
{
public static void main(String[] args)
{
QueueADT queue = new LinkedQueue();
//put some stuff in the queue: 0,2,4,..,14
for (int i=0; i<8; i++)
queue.enqueue(i*2);
System.out.println(" ** Initial queue **");
printQueue(queue);
//dequeue 4 items
for (int i=0; i<4; i++)
queue.dequeue();
System.out.println(" ** After dequeueing 4 items **");
printQueue(queue);
//enqueue 7 more: 1,2,..,7
for (int i=0; i<7; i++)
queue.enqueue(i+1);
System.out.println(" ** After enqueueing 7 more items **");
printQueue(queue);
}
//----------------------------------------------------------
// Prints elements of queue, restoring it before returning
//----------------------------------------------------------
public static void printQueue(QueueADT queue)
{
QueueADT temp = new LinkedQueue();
//print everything in the queue, putting elements
//back into a temporary queue
while (!queue.isEmpty())
{
int val = queue.dequeue();
temp.enqueue(val);
System.out.print(val + " ");
}
System.out.println ();
//restore the original queue
while (!temp.isEmpty())
{
int val = temp.dequeue();
queue.enqueue(val);
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started