/341. Flatten Nested List Iterator

341. Flatten Nested List Iterator

Medium
Stack65.6% acceptance

Given a nested list of integers, where each element is either an integer or a list (which may contain integers or other lists), implement a class IntegerListIterator that flattens the nested structure and iterates through all integers in order. The class must support the following methods:

- IntegerListIterator(nested_integer_list): Initializes the iterator with the nested list.

- next(): Returns the next integer in the flattened list.

- has_next(): Returns True if there are more integers to iterate, otherwise False.

The nested list is represented as a list of integers or lists, e.g., [1, [2, [3, 4]], 5].

To test, repeatedly call next() while has_next() is True, collecting the results into a list. The final list should match the fully flattened list of integers.

Example 1

Input: nested_integer_list = [[3,2],5,[7,[8,9]]]

Output: [3,2,5,7,8,9]

Explanation: Flattened order is [3,2,5,7,8,9].

Example 2

Input: nested_integer_list = [10,[20,[30,40]],50]

Output: [10,20,30,40,50]

Explanation: Flattened order is [10,20,30,40,50].

Example 3

Input: nested_integer_list = [[-1,-2],[-3],[-4,[-5]]]

Output: [-1,-2,-3,-4,-5]

Explanation: Flattened order is [-1,-2,-3,-4,-5].

Constraints

  • 1 <= length of nested_integer_list <= 500
  • Each element is either an integer in [-106, 106] or a list
  • Nesting depth is arbitrary but finite
Python (current runtime)

Case 1

Input: nested_integer_list = [[0],[1,[2,3]],4]

Expected: [0,1,2,3,4]

Case 2

Input: nested_integer_list = [[],[5],[[6,7]],8]

Expected: [5,6,7,8]

Case 3

Input: nested_integer_list = [100, [200, [300, [400]]]]

Expected: [100,200,300,400]