题目:
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]
.
1 /** 2 * // This is the interface that allows for creating nested lists. 3 * // You should not implement it, or speculate about its implementation 4 * public interface NestedInteger { 5 * 6 * // @return true if this NestedInteger holds a single integer, rather than a nested list. 7 * public boolean isInteger(); 8 * 9 * // @return the single integer that this NestedInteger holds, if it holds a single integer 10 * // Return null if this NestedInteger holds a nested list 11 * public Integer getInteger(); 12 * 13 * // @return the nested list that this NestedInteger holds, if it holds a nested list 14 * // Return null if this NestedInteger holds a single integer 15 * public List<NestedInteger> getList(); 16 * } 17 */ 18 public class NestedIterator implements Iterator<Integer> { 19 private Iterator<Integer> nested; 20 private List<Integer> nes=new ArrayList<Integer>(); 21 private int index=0; 22 public NestedIterator(List<NestedInteger> nestedList) { 23 NesIterator(nestedList); 24 nested=nes.iterator(); 25 } 26 27 private void NesIterator(List<NestedInteger> nestedList) { 28 for(int i=0;i<nestedList.size();i++) 29 { 30 if(nestedList.get(i).isInteger()) 31 { 32 nes.add(nestedList.get(i).getInteger()); 33 } 34 else { 35 NesIterator(nestedList.get(i).getList()); 36 } 37 } 38 } 39 @Override 40 public Integer next() { 41 index++; 42 return nested.next(); 43 } 44 45 @Override 46 public boolean hasNext() { 47 if(index<nes.size()) 48 return true; 49 return false; 50 } 51 } 52 53 /** 54 * Your NestedIterator object will be instantiated and called as such: 55 * NestedIterator i = new NestedIterator(nestedList); 56 * while (i.hasNext()) v[f()] = i.next(); 57 */