231k views
10 votes
Write the function evens which takes in a queue by reference and changes it to only contain the even elements. That is, if the queue initially contains 3, 6, 1, 7, 8 then after calling odds, the queue will contain 6, 8. Note that the order of the elements in the queue remains the same. For full credit, no additional data structures (queues, stacks, vectors, etc.) should be used. Assume all libraries needed for your implementation have already been included.

User Man Of God
by
5.6k points

1 Answer

8 votes

Answer:

Step-by-step explanation:

The following code is written in Java it goes through the queue that was passed as an argument, loops through it and removes all the odd numbers, leaving only the even numbers in the queue. It does not add any more data structures and finally returns the modified queue when its done.

public static Queue<Integer> evens(Queue<Integer> queue) {

int size = queue.size();

for(int x = 1; x < size+1; x++) {

if ((queue.peek() % 2) == 0) {

queue.add(queue.peek());

queue.remove();

} else queue.remove();

}

return queue;

}

User Nhrcpt
by
6.0k points