341. Flatten Nested List Iterator
You are given a nested list of integers nestedList
. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the NestedIterator
class:
NestedIterator(List<NestedInteger> nestedList)
Initializes the iterator with the nested listnestedList
.int next()
Returns the next integer in the nested list.boolean hasNext()
Returnstrue
if there are still some integers in the nested list andfalse
otherwise.
Example 1:
Input: nestedList = [[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: nestedList = [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].
Constraints:
1 <= nestedList.length <= 500
- The values of the integers in the nested list is in the range
[-106, 106]
.
/** * // 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 empty list if this NestedInteger holds a single integer * public List<NestedInteger> getList(); * } */ public class NestedIterator implements Iterator<Integer> { Stack<NestedInteger> stack; public NestedIterator(List<NestedInteger> nestedList) { stack = new Stack(); flatten(nestedList); } @Override public Integer next() { return hasNext() ? stack.pop().getInteger() : null; } @Override public boolean hasNext() { while(!stack.isEmpty()) { if(stack.peek().isInteger()) return true; flatten(stack.pop().getList()); } return false; } public void flatten(List<NestedInteger> nestedList) { for(int i = nestedList.size() - 1; i >= 0; i--) { stack.push(nestedList.get(i)); } } }
getlist是返回一个list,getinteger是返回一个integer。
需要一个flatten方法,把不是integer而是nested list放入stack。
初始化的时候先把初始nestedlist放进去,next是先判断hasnext,然后pop一个nestedlist然后getinteger。
hasnext是先判断空,然后如果peek的nestedlist是isinteger,说明这个nestedlist只有integer,return true,否则继续call flatten