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:
Input: [[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:
Input: [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]
.
思路:for each的循环!判断i是不是integer,如果不是,就继续flatten它
注意要初始化
flattenedList = new LinkedList<Integer>();
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class NestedIterator implements Iterator<Integer> { LinkedList<Integer> flattenedList; Iterator<Integer> iterator; public NestedIterator(List<NestedInteger> nestedList) { //注意要初始化 flattenedList = new LinkedList<Integer>(); flatten(nestedList); iterator = flattenedList.iterator(); } public void flatten(List<NestedInteger> nestedList) { for (NestedInteger ni : nestedList) { if (ni.isInteger()) { flattenedList.add(ni.getInteger()); }else { flatten(ni.getList()); } } } @Override public Integer next() { return iterator.next(); } @Override public boolean hasNext() { return iterator.hasNext(); } } /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i = new NestedIterator(nestedList); * while (i.hasNext()) v[f()] = i.next(); */