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:
Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false,
the order of elements returned by next should be: [1,1,2,1,1].
Example 2:
Input: [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false,
the order of elements returned by next should be: [1,4,6].
stack。
思路:因为有时候会碰到暂存的情况,所以要用stack。但因为想要前面的nested最后先被叫到,所以每次压栈要从后往前压。
初始化:从后往前压一次。
next:直接pop顶层的integer。(默认顶层元素现在都是integer,会在hasNext里处理好)
hasNext:先while循环栈顶不是平int的情况,把nested展开从后往前再压进去子元素。如果处理完还是非空的话才是真的有next()。
细节:
1.处理展开顶层的逻辑要放在hasNext里,而不是next里。这样才能保证只有真的有数字才会叫next(),避免报runtime错误。比如corner case[[]],其实里面什么integer都没有你根本不应该叫到next方法,初始化的时候stack里还是有元素的,所以你要在hasNext里展一下。
实现:
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public 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 ListgetList(); * } */public class NestedIterator implements Iterator { private Stack stack; public NestedIterator(List nestedList) { this.stack = new Stack<>(); 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() { // P1: 注意这部分顶层处理要放在hasNext里不可以next里。不然对[[]]这种corner case会在hasNext()的时候好好的,在next()的时候runtime error。 while (!stack.isEmpty() && !stack.peek().isInteger()) { List list = stack.peek().getList(); stack.pop(); for (int i = list.size() - 1; i >= 0; i--) { stack.push(list.get(i)); } } return !stack.isEmpty(); }}/** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i = new NestedIterator(nestedList); * while (i.hasNext()) v[f()] = i.next(); */