/* * 341. Flatten Nested List Iterator * 2016-7-10 by Mingyang * 这个题目又是Iterator,这里不能直接用那个东西了 * 而且我们知道List可以从最后一个往前遍历 */ class NestedIterator implements Iterator<Integer> { Stack<NestedInteger> stack = new Stack<>(); public NestedIterator(List<NestedInteger> nestedList) { for(int i = nestedList.size() - 1; i >= 0; i--) { stack.push(nestedList.get(i)); } } @Override public Integer next() { return stack.pop().getInteger(); } @Override public boolean hasNext() { while(!stack.isEmpty()) { NestedInteger curr = stack.peek(); if(curr.isInteger()) { return true; } stack.pop(); for(int i = curr.getList().size() - 1; i >= 0; i--) { stack.push(curr.getList().get(i)); } } return false; } @Override public void remove() { // TODO Auto-generated method stub } } interface NestedInteger { // @return true if this NestedInteger holds a single integer, rather than a nested list. public boolean isInteger(); // @return the single integer that this NestedInteger holds, if it holds a single integer // Return null if this NestedInteger holds a nested list public Integer getInteger(); // @return the nested list that this NestedInteger holds, if it holds a nested list // Return null if this NestedInteger holds a single integer public List<NestedInteger> getList(); }