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

Write a method in Java that will return a Queue containing every other number of

ID: 3824980 • Letter: W

Question

Write a method in Java that will return a Queue containing every other number of a given Queue. For example, if the given queue contains {12, 14, 15, 20, 25} then the returned queue must contain {12, 15, 25}.

Note: Once the execution returns to the caller method, the given queue should contain exactly the same elements in the same sequence as before making the call. Assume that a standard Queue class is available. You may NOT create any temporary container inside the method. That is, creation of arrays, vectors, lists, stacks, or any other temporary queue that is not returned is prohibited in this method. The header of the method is provided below.

}

Explanation / Answer

Method in bold is the required method.. Rest of the code is tester to demonstarte.

import java.util.*;

public class HelloWorld{
public static Queue getEveryOtherElements(Queue q){
Iterator it = q.iterator();
Queue everyOther = new LinkedList<>();
for (; it.hasNext();){
everyOther.add(it.next());
if(it.hasNext())
it.next();
}
return everyOther;
}

public static void main(String []args){
Queue<Integer> q = new LinkedList<>();
q.add(1);
q.add(2);
q.add(3);
q.add(4);
q.add(5);
q.add(6);
q.add(7);
System.out.println("Before calling method");
for(Integer i : q) {
System.out.print(i + " ");
}
System.out.println();
Queue<Integer> res = getEveryOtherElements(q);
System.out.println("After calling method");
for(Integer i : q) {
System.out.print(i + " ");
}
System.out.println();
System.out.println("New queue");
for(Integer i : res) {
System.out.print(i + " ");
}
System.out.println();

}
}

Sample run

$ java -Xmx128M -Xms16M HelloWorld
Before calling method
1 2 3 4 5 6 7
After calling method
1 2 3 4 5 6 7
New queue
1 3 5 7

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote