Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

complete following 2 methods: printQueue method and printQueue2 method Write an

ID: 3719930 • Letter: C

Question

complete following 2 methods: printQueue method and printQueue2 method

Write an implementation of the printQueue method which removes and prints each element in the Queue, restoring the queue before it returns. It uses a temporary queue that actually holds the same information as the original queue.

// **************************************************************

// 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)

{

//complete here

}

//write a printQueue method that prints the queue and restores it to its original form without using an auxiliary data structure (stack,queue, etc.). but printQueue2 method can do the same thing as printQueue method.

public static void printQueue2(QueueADT queue)

{// complete here

}

}

}

Explanation / Answer

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package javaapplication38;
import java.util.*;

public class QueueTest {

public static void main(String[] args) {
int i;
Queue<Integer> q=new LinkedList();
for(i=1;i<5;i++)
q.offer(i);
q=printQueue(q);
//while(!(q.isEmpty()))
// System.out.print(q.poll()+" ");
q=printQueue2(q);
q=printQueue2(q);
while(!(q.isEmpty()))
System.out.print(q.poll()+" ");
}
public static Queue<Integer> printQueue(Queue<Integer> q)
{
Queue<Integer> q1=new LinkedList();
while(!(q.isEmpty()))
{
System.out.print(q1.offer(q.poll())+" ");

}
// for(int i=11;i<15;i++)
// q1.offer(i);
System.out.println();
return q1;
}
public static Queue<Integer> printQueue2(Queue<Integer> q)
{
Integer a;
if(!q.isEmpty())
{
a=q.poll();
printQueue2(q);
q.offer(a);
}
return q;
}
}

run:
true true true true   
1 2 3 4 BUILD SUCCESSFUL (total time: 1 second)