A nested list holds items that are either integers or other nested lists, to any depth. For example, [[4,-2],[],7,[[9]]] holds a list of two integers, an empty list, the integer 7, and a list holding a list holding 9.
Write the class NestedIterator, which hands out the integers of a nested list one at a time, in the order they appear when the list is read left to right:
NestedIterator(nestedList) sets up the iterator over nestedList.next() returns the next integer.hasNext() returns true if at least one integer is still to come, and false otherwise.Each item arrives as a NestedInteger, which you can ask isInteger(), then either getInteger() for an integer item or getList() for a list item.
Your iterator is checked by draining it: the tests create it, then call next() for as long as hasNext() returns true, and collect what next() returns. That collected list must be the integers in order. Empty lists contain no integers, so they must never make hasNext() answer true.
Reading left to right: 4 and -2 from the first list, nothing from the empty list, then 7, then 9 from two levels down.
Only two integers are anywhere in the list. The empty lists, including the one after 5 and the one at the very end, produce nothing, so hasNext() must return false once 5 is handed out.
There is nothing to iterate over: the first hasNext() returns false.
Constraints
0 <= nestedList.length <= 500, and every inner list also holds at most 500 items.5000 levels deep, counting nestedList itself as level 1.2 * 10⁴ integers and at most 10⁴ inner lists.-10⁶ and 10⁶, inclusive.Flattening is a depth-first walk over the nested lists. To produce one value per call instead of all at once, keep the walk's state yourself: a stack of the lists you are inside and how far along each one you are.
[[4,-2],[],7,[[9]]]