0

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.

1
  • I would suggest you use the ConcurrentLikedDeque. Here is the API for it ConcurrentLinkedDeque. If you already have a class with methods like enqueue, dequeue etc, you can wrap the ConcurrentLinkedDeque into your class and use it as your main data structure for storing our objects. Commented Nov 22, 2012 at 12:45

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.