Queue Challenges and Hacks
import java.util.LinkedList;
import java.util.Queue;
public class QueueMerger {
public Queue<Integer> mergeQueues(Queue<Integer> a, Queue<Integer> b) {
Queue<Integer> c = new LinkedList<Integer>();
// gets peeks of each queue if both are not empty
while (a.peek() != null && b.peek() != null) {
// compares values of peeks, then appends to queue c
if (a.peek() < b.peek()) {
c.add(a.peek());
a.remove();
} else {
c.add(b.peek());
b.remove();
}
}
// if b is empty but a is not
while (a.peek() != null) {
c.add(a.peek());
a.remove();
}
// if a is empty but b is not
while (b.peek() != null) {
c.add(b.peek());
b.remove();
}
return c;
}
public void printQueue(Queue<Integer> q) {
System.out.print("Queue: ");
for (Integer data : q)
System.out.print(data + " ");
System.out.println();
}
public static void main(String[] args) {
// create queue manager 1 and 2
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
// add objects to queue and print both
q1.add(1);
q1.add(3);
q1.add(4);
q1.add(5);
q1.add(13);
q2.add(2);
q2.add(5);
q2.add(6);
q2.add(7);
q2.add(9);
q2.add(10);
q2.add(17);
// merge queues
QueueMerger qm = new QueueMerger();
qm.printQueue(q1);
qm.printQueue(q2);
Queue<Integer> qmm = qm.mergeQueues(q1, q2);
// print merged queue
qm.printQueue(qmm);
}
}
QueueMerger.main(null);