Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list — whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]]
,
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]
.
Example 2:
Given the list [1,[4,[6]]]
,
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]
.
Solution. This problem is the same as deepIterator. Each time, we store the iterator of the list in stack. But in my previous deepIterator, I didn’t handle when a list is empty.
For this problem, I use currInteger to tell if iterator has next.
The main part is the refresh() function. It iterates until it finds an element is Integer. When current iterator doesn’t has next or list is totally empty, it pops the stop. When current element is a list, it pushes to stack.
private void refresh() { currInteger = null; while (!s.isEmpty()) { if (!s.peek().hasNext()) { // iterator is empty. Another situation could be that iterator for the list is empty at all s.pop(); continue; } NestedInteger curr = s.peek().next(); if (curr.isInteger()) { currInteger = curr.getInteger(); return; } // comes to here, it means it is a list s.push(curr.getList().iterator()); } }
Check my code on github: link