You’re given a nested list of integers. Each element is either an integer or a list whose elements may also be integers or other integer lists. Your task is to implement an iterator to flatten the nested list.
You will have to implement the Nested Iterator class. This class has the following functions:
Constraints
We’ll use a stack to solve this problem. The stack will be used to store the integer and list of integers on the iterator object. We’ll push all the nested list data in the stack in reverse order in the constructor. The elements are pushed in reverse order because the iterator is implemented using a stack. In order to process the nested list correctly, the elements need to be accessed in the order they appear in the original nested list.
Here is how we implement the NestedIterator class methods to solve the above problem:
You’re given a nested list of integers. Each element is either an integer or a list whose elements may also be integers or other integer lists. Your task is to implement an iterator to flatten the nested list.
You will have to implement the Nested Iterator class. This class has the following functions:
Constraints
We’ll use a stack to solve this problem. The stack will be used to store the integer and list of integers on the iterator object. We’ll push all the nested list data in the stack in reverse order in the constructor. The elements are pushed in reverse order because the iterator is implemented using a stack. In order to process the nested list correctly, the elements need to be accessed in the order they appear in the original nested list.
Here is how we implement the NestedIterator class methods to solve the above problem: