dj5 dj5 - 1 month ago 10
Java Question

Merging Sorted Lists with Iterators in Java

The method I am using takes two sorted lists and returns a single list containing all of the elements in the two original lists, in sorted order.

For example, if the original lists are (1, 4, 5) and (2, 3, 6) then the result list would be (1, 2, 3, 4, 5, 6).

Is there something I am missing?

public static<E extends Comparable<E>> List<E> mergeSortedLists(List<E> a, List<E> b) {
List<E> result = new ArrayList<E>();

PushbackIterator<E> aIter = new PushbackIterator<E>(a.iterator());
PushbackIterator<E> bIter = new PushbackIterator<E>(b.iterator());

while (aIter.hasNext() && bIter.hasNext()) {
if (aIter.next().compareTo(bIter.next()) < 0) {
result.add(aIter.next());
}
if (bIter.next().compareTo(bIter.next()) > 0){
result.add(bIter.next());
}
}
while (aIter.hasNext()) {
result.add(aIter.next());
}
while (bIter.hasNext()) {
result.add(bIter.next());
}
return result;
}

Answer

I'm going to assume you intended something like this with your use of PushbackIterator:

while (aIter.hasNext() && bIter.hasNext()) {
    E aElem = aIter.next();
    E bElem = bIter.next();
    if (aElem.compareTo(bElem) <= 0) {
        result.add(aElem);
        aIter.pushback(bElem);
    } else {
        result.add(bElem);
        bIter.pushback(aElem);
    }
}
Comments