|
| 1 | +package design; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Iterator; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +/** |
| 8 | + * Created by gouthamvidyapradhan on 30/11/2017. |
| 9 | + * |
| 10 | + * Given a nested list of integers, implement an iterator to flatten it. |
| 11 | +
|
| 12 | + Each element is either an integer, or a list -- whose elements may also be integers or other lists. |
| 13 | +
|
| 14 | + Example 1: |
| 15 | + Given the list [[1,1],2,[1,1]], |
| 16 | +
|
| 17 | + By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. |
| 18 | +
|
| 19 | + Example 2: |
| 20 | + Given the list [1,[4,[6]]], |
| 21 | +
|
| 22 | + By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. |
| 23 | + */ |
| 24 | +public class NestedIterator implements Iterator<Integer>{ |
| 25 | + |
| 26 | + private List<Integer> result; |
| 27 | + private int curr, size; |
| 28 | + |
| 29 | + // This is the interface that allows for creating nested lists. |
| 30 | + // You should not implement it, or speculate about its implementation |
| 31 | + public interface NestedInteger{ |
| 32 | + //@return true if this NestedInteger holds a single integer, rather than a nested list. |
| 33 | + public boolean isInteger(); |
| 34 | + |
| 35 | + // @return the single integer that this NestedInteger holds, if it holds a single integer |
| 36 | + // Return null if this NestedInteger holds a nested list |
| 37 | + public Integer getInteger(); |
| 38 | + |
| 39 | + // @return the nested list that this NestedInteger holds, if it holds a nested list |
| 40 | + // Return null if this NestedInteger holds a single integer |
| 41 | + public List<NestedInteger> getList(); |
| 42 | + } |
| 43 | + |
| 44 | + public NestedIterator(List<NestedInteger> nestedList) { |
| 45 | + this.result = new ArrayList<>(); |
| 46 | + curr = 0; |
| 47 | + flatten(result, nestedList); |
| 48 | + size = result.size(); |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public Integer next() { |
| 53 | + if(curr < size){ |
| 54 | + return result.get(curr++); |
| 55 | + } |
| 56 | + return -1; |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public boolean hasNext() { |
| 61 | + return curr < size; |
| 62 | + } |
| 63 | + |
| 64 | + public static void main(String[] args) { |
| 65 | + |
| 66 | + } |
| 67 | + |
| 68 | + private void flatten(List<Integer> flatList, List<NestedInteger> nestedList){ |
| 69 | + for(NestedInteger n : nestedList){ |
| 70 | + if(n.isInteger()){ |
| 71 | + flatList.add(n.getInteger()); |
| 72 | + } else{ |
| 73 | + flatten(flatList, n.getList()); |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments