I have an assignment in which I have a queue (from the class ArrayQueues) for which I am supposed to write a method in another class (Queues) that splits the queue into two. The method, split(Queue queue), takes the queue and returns another queue with half the items of the first queue, but it does not simply take the first half or second half. It takes every other item in the original queue and distributes the items evenly. This is how I am going about it:
public class Queues{
public static <E> Queue<E> split(Queue<E> queue){
Queue<E> queue1 = new ArrayQueue<>(queue.capacity());
Queue<E> queue2 = new ArrayQueue<>(queue.capacity());
int size = queue.size();//I did this because the size of queue changes after every iteration due to it being dequeued
for(int i = 0; i < size;i++){
if(i%2==0){
queue2.enqueue(queue.dequeue());//adds item from queue to queue2 and removes that item from queue
}else{
queue1.enqueue(queue.dequeue());//add item from queue to queue1 and removes item from queue
}
queue = queue1;
return queue2;
}
}
The result I get is queue2 and queue1 both have the appropriate items (every other item from queue). However, the original queue is now empty, and I understand that it would be since I have been dequeueing it. But I set
queue = queue1
Why is it empty even after I set it to queue1?