Write a function called max that takes as input a reference
Write a function called max that takes as input a reference to a single queue of integers and returns the largest integer in the queue without destroying the queue. That is, the queue you return must be in the same state as when you called the function max. In order to be effecient, your function should not create any copies of the queue. However, you are permitted to modify the queue as you search for the largest element . You may assume that any queue passed to max always has at least one element , so the notion of largest elemet is well defined.
Solution
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
/**
* Checking max element from Queue using iterator
*
* @param queue
* @return
*/
public int max(Queue<Integer> queue) {
int max = 0;
// access via Iterator
Iterator<Integer> iterator = queue.iterator();
while (iterator.hasNext()) {
int element = iterator.next();
if (max < element) {
max = element;
}
}
/**
* We are printing front element of queue for checking state of queue
*/
System.out.println(\"Checking state of Queue\");
System.out.println(\"Peek element from queue \" + queue.peek());
return max;
}
public static void main(String[] args) {
/**
* instance creation
*/
QueueExample qs = new QueueExample();
Queue<Integer> queue = new LinkedList<Integer>();
/**
* Adding into Queue
*/
queue.add(10);
queue.add(20);
queue.add(30);
queue.add(40);
queue.add(50);
/**
* calling max method
*/
int largest = qs.max(queue);
System.out.println(\"Max Element is :\" + largest);
System.out.println(\"Checking state of Queue\");
System.out.println(\"Peek element from queue \" + queue.peek());
}
}
/************************Output**********************/
Checking state of Queue
Peek element from queue 10
Max Element is :50
Checking state of Queue
Peek element from queue 10
Thanks a lot

