To complete the meld in linear time,
we use two chain iterators ia
and ib
to march through the chains a
and b respectively. When we fall off of
one chain, the balance of the remaining chain is copied over to the
melded chain c.
Since elements from a
and b are to be added to the end of the chain
c, we use the
single parameter
add method of
ExtendedChain (this appends an element to the
right end of the chain).
The code is given below.
public class MeldExtendedChain
{
/** meld alternately from a and b */
public static ExtendedChain meld(ExtendedChain a, ExtendedChain b)
{
// initialize iterators for a and b
Iterator ia = a.iterator(); // iterator for a
Iterator ib = b.iterator(); // iterator for b
// create result chain
ExtendedChain c = new ExtendedChain();
// do the meld
while (ia.hasNext() && ib.hasNext())
{
c.add(ia.next()); // append at right end
c.add(ib.next()); // append at right end
}
// append the rest
// at most one of a and b can be nonempty now
while (ia.hasNext())
c.add(ia.next());
while (ib.hasNext())
c.add(ib.next());
return c;
}
}