简体   繁体   中英

Merge Queues in Java

I was wondering whats the best way to write a method to merge an ArrayQueue with another Queue without removing any elements from the q thats passed.

eg. queue1 = [1,2,3,4] and queue2 = [5,6,7,8,9,10].

When queue1.mergeQs(queue2) was called it would create queue1 = [1,5,2,6,3,7,4,8,9,10] whilst queue2 would remain [5,6,7,8,9,10]

    public void mergeQs(ArrayQmerge q){}

This way seems harder to implement than if you were to pass both Queues and return a new merged Queue. Thanks.

Just to clarify, i'm looking for a method to interleave the elements from the two queues.

One detail that might help you is that private fields are visible between different object of the same class in Java. That means that as long as you only intend to merge queues of your own class, your code has full access to all internal fields, such as the array you use to store your elements.

For the simplest case, where all elements are stored in a linear array with the queue head being at index zero, something like this might be a start:

public void mergeQs(ArrayQmerge q) {
    Object[] array = new Object[this.size() + q.size()];

    int i;
    int o;

    // Interleave elements
    for (i = 0, o = 0; i < this.size() && i < q.size(); ++i) {
        array[o++] = this.array[i];
        array[o++] = q.array[i];
    }

    // Copy the remaining elements
    while (i < this.size()) {
        array[o++] = this.array[i++];
    }

    while (i < q.size()) {
        array[o++] = q.array[i++];
    }

    this.array = array;
}

您可以在merge方法中本地创建一个新的Queue,然后将您的类的队列分配给本地版本。

Since you are using your own homebrew ArrayQueue then this is conjecture.

Creating a new queue and returning is as I think you already say is way easier, and more efficient, as inserting elements into an Array backed structure will involve shuffling the rest of the elements down one position for each insert op.

An alternative is to implement public void mergeQs(ArrayQmerge q) by swapping out the underlying array you have backing it. So you get the same easy implementation as returning a new Queue but with the same in place side effect.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM