call(back)
Algorithms & Data StructureseasySign in to star problems

Compound Iterator

Chain any number of iterables into one iterator with a hasNext() / next() interface: CompoundIterator(...iterables) yields every element of the first iterable, then the second, and so on, skipping the empty ones. Calling hasNext() repeatedly must not consume anything.

it = CompoundIterator([1, 2], [], [3], [], [], [4, 5])   ->  1, 2, 3, 4, 5

Hints

Hint 1

Keep a queue of iterators. Advancing takes the next element from the front iterator and drops iterators as they run out.

Hint 2

Fill a one-element lookahead in the constructor and after every next(); hasNext() only reports whether it is filled, so asking twice never skips anything.

Asked at