99.4k views
3 votes
write a method that, given a non-empty queue of integers, returns the largest value. the queue should have the same contents as before the call. of course, you can remove elements to inspect them, but you need to add them back into the queue.

User Randomx
by
7.0k points

1 Answer

2 votes

Final answer:

To find the largest value in a non-empty queue of integers, you can use a method that iterates through the queue, removing elements one by one to inspect them and stores the largest value using the Math.max function.

Step-by-step explanation:

To find the largest value in a non-empty queue of integers, you can use the following method:

public static int findLargestValue(Queue<Integer> queue) {
int largestValue = Integer.MIN_VALUE;
int size = queue.size();

for (int i = 0; i < size; i++) {
int value = queue.poll();
largestValue = Math.max(largestValue, value);
queue.offer(value);
}

return largestValue;
}

This method iterates through the queue, removing elements one by one to inspect them. The largest value is stored in the largestValue variable using the Math.max function. Finally, the elements are added back into the queue using the offer method.

User Jiggysoo
by
8.5k points