When creating 2 Queues like this:
ArrayQueue q1 = new ArrayQueue();
ArrayQueue q2 = new ArrayQueue();
for (int i = 0; i < 5; i++) {
q1.enqueue(new Integer(i));
}
for (int i = 5; i < 10; i++) {
q2.enqueue(new Integer(i));
}
System.out.println("q1: " + q1);
System.out.println("q2: " + q2);
It outputs: q1: 4,3,2,1,0
and q2: 9,8,7,6,5
.
I need a method that merges Queue q2
into Queue q1
with interleaved elements. So if println
'd again would output: q1: 0,5,1,6,2,7,3,8,4,9
and q2: 9,8,7,6,5
.
My class contains all the appropriate methods enqueue
, dequeue
, peek
, isEmpty
, size
, doubleSize
... my method name is:
public void mergedQs(ArrayQueue q) {
}
Basically i want to add objects to two queues, then merge the second queue into the first(not just add them). Ideally i want to avoid casting them or using an ArrayList as i want them to remain Queues.
You might find this useful. It merges any number of queues.
public static <T> Queue<T> mergeQs(Queue<T> ... qs) {
Queue<T> ret = new ConcurrentLinkedQueue<T>();
boolean more;
do {
more = false;
for (Queue<T> q : qs)
if (!q.isEmpty()) {
ret.add(q.remove());
more = true;
}
} while(more);
return ret;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.