|
| 1 | +// Flatten the list at creation/constructor time, and then iterate through the flattened list |
| 2 | +classNestedIterator(nestedList:List<NestedInteger>) { |
| 3 | +val stack=LinkedList<Int>() |
| 4 | + |
| 5 | +init { |
| 6 | + dfs(nestedList) |
| 7 | + stack.reverse() |
| 8 | + } |
| 9 | + |
| 10 | +funnext()= stack.removeLast() |
| 11 | + |
| 12 | +funhasNext()= stack.isNotEmpty() |
| 13 | + |
| 14 | +privatefundfs(nested:List<NestedInteger>) { |
| 15 | +for (nin nested) { |
| 16 | +if (n.isInteger()) |
| 17 | + stack.addLast(n.getInteger()) |
| 18 | +else |
| 19 | + dfs(n.getList()) |
| 20 | + } |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +// Dynamically ("on-the-go") flatten the list while iterating |
| 25 | +classNestedIterator(nestedList:List<NestedInteger>) { |
| 26 | + |
| 27 | +val stack=LinkedList<NestedInteger>() |
| 28 | + |
| 29 | +init { |
| 30 | + stack.addAll(nestedList.reversed()) |
| 31 | + } |
| 32 | + |
| 33 | +funnext():Int { |
| 34 | +return stack.removeLast().getInteger() |
| 35 | + } |
| 36 | + |
| 37 | +funhasNext():Boolean { |
| 38 | +while (stack.isNotEmpty()&&!stack.peekLast().isInteger()) { |
| 39 | + stack.addAll(stack.removeLast().getList().reversed()) |
| 40 | + } |
| 41 | + |
| 42 | +return stack.isNotEmpty() |
| 43 | + } |
| 44 | +} |