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