How do you generate sorted numbers of 2 queues without using an additional data structure?

advertisements

I dont know if this is possible at all but:

Say we got 2 queues: queue1 and queue2, and each queue includes (natural) numbers that are sorted from lowest to greatest (queue1.head() and queue2.head() return the smallest value of queue1 / queue2).

How could you output the numbers that are included in queue1 and queue2 in sorted (from lowest to greatest) order without using additional data structure?


Like this:

while (!queue1.isEmpty() || !queue2.isEmpty()) {
     if (queue1.isEmpty()) {
         System.out.println(queue2.remove());
     } else if (queue2.isEmpty()) {
         System.out.println(queue1.remove());
     } else if (queue1.peek() < queue2.peek()) {
         System.out.println(queue1.remove());
     } else {
         System.out.println(queue2.remove());
     }
}

First you need to take the case when one of queues is empty, so then you output from other. Then you peek in both and compare them and take the smallest. You do this until both queues are empty.