You are given a nested list of integer,s nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the NestedIterator class:
NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.
int next() Returns the next integer in the nested list.
boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.
Your code will be tested with the following pseudocode:
1
2
3
4
5
initialize iterator with nestedList
res =[]while iterator.hasNext() append iterator.next() to the end of res
return res
If res matches the expected flattened list, then your code will be judged as correct.
Input: nestedList =[[1,1],2,[1,1]]Output: [1,1,2,1,1]Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:[1,1,2,1,1].
Example 2:
1
2
3
Input: nestedList =[1,[4,[6]]]Output: [1,4,6]Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:[1,4,6].
To flatten a nested list, you can either use recursion to flatten it completely and then iterate over a flat list or use a stack to manage the nested structure iteratively.
Above approach is good, but it is very eager in nature, where we are eagerly creating a list of flattened integers and then returning. Here is the approach:
Flatten the nested list recursively.
Store the flattened list in a simple list structure.
In the constructor, elements from nestedList are inserted into the stack in reverse order to ensure the first element can be accessed first when popped. In the hasNext() method, the current top of the stack is checked: if it is an integer, it is returned and removed from the stack; if it is a list, it is further flattened. This method iteratively flattens the nested list by processing elements from back to front.
Here is the approach:
Use a stack to keep track of elements.
Push elements onto the stack from back to front.
Flatten nested lists iteratively by checking the top of the stack and processing lists as needed.