We can use essentially the same code as used in Exercise 15 to merge two chains.
We must change all occurrences of ExtendedChain
to CircularList.
The modified code is given below.
public class MergeCircularList
{
/** merge the sorted lists a and b */
public static CircularList merge(CircularList a, CircularList b)
{
// initialize iterators for a and b
Iterator ia = a.iterator(); // iterator for a
Iterator ib = b.iterator(); // iterator for b
Comparable elementA = null; // current element of a
if (ia.hasNext())
elementA = (Comparable) ia.next();
Object elementB = null; // current element of b
if (ib.hasNext())
elementB = ib.next();
// create result list
CircularList c = new CircularList();
// do the merge
while (elementA != null && elementB != null)
{
if (elementA.compareTo(elementB) <= 0)
{// elementA goes next
c.add(elementA);
if (ia.hasNext())
elementA = (Comparable) ia.next();
else
elementA = null;
}
else
{// elementB goes next
c.add(elementB);
if (ib.hasNext())
elementB = ib.next();
else
elementB = null;
}
}
// add remaining elements
if (elementA != null)
c.add(elementA);
if (elementB != null)
c.add(elementB);
// 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;
}
}
-
-
- (b)
-
In each iteration of the first
while loop, we
move one node right
either in a or
either in b.
So, the complexity of this loop is
O(a.size + b.size).
The complexity of the second while loop
is O(a.size), and that of the third
loop is O(b.size).
So, the overall complexity is
O(a.size + b.size).
- (c)
-
The codes and output are in the files
MergeCircularList.*.