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]
.
题目
将Nested List展平,像访问一个一维列表一样访问嵌套列表。
思路
queue
代码
1 public class NestedIterator implements Iterator<Integer> { 2 3 Queue<Integer> queue; 4 5 public NestedIterator(List<NestedInteger> nestedList) { 6 queue = new LinkedList<>(); 7 helper(nestedList); 8 } 9 10 @Override 11 public Integer next() { 12 return queue.poll(); 13 } 14 15 @Override 16 public boolean hasNext() { 17 return !queue.isEmpty(); 18 } 19 private void helper(List<NestedInteger> nestedList){ 20 for(NestedInteger n:nestedList){ 21 if(n.isInteger()){ 22 queue.add(n.getInteger()); 23 }else{ 24 helper(n.getList()); 25 } 26 } 27 } 28 }