# 0341. Flatten Nested List Iterator ###### tags: `Leetcode` `Medium` `Stack` Link: https://leetcode.com/problems/flatten-nested-list-iterator/ ## 思路 In the constructor, we push all the nestedList into the stack from back to front, so when we pop the stack, it returns the very first element. Second, in the hasNext() function, we peek the first element in stack currently, and if it is an Integer, we will return true and pop the element. If it is a list, we will further flatten it. This is iterative version of flatting the nested list. 因为在呼叫next()之前,一定会呼叫hasNext(),所以一定要把flatten的过程写在hasNext()里面 不然有可能在flatten之前nestedList长这样[[]] flatten之后里面是空的 就不知道应该要return什么了 这种情况应该在hasNext的时候发现 这样hasNext会直接return false就不会再有后续 next() ## Code ```java= public class NestedIterator implements Iterator<Integer> { Stack<NestedInteger> stack; public NestedIterator(List<NestedInteger> nestedList) { stack = new Stack<>(); addToStack(nestedList); } @Override public Integer next() { return stack.pop().getInteger(); } @Override public boolean hasNext() { while(!stack.isEmpty() && !stack.peek().isInteger()){ List<NestedInteger> currList = stack.pop().getList(); addToStack(currList); } return !stack.isEmpty(); } public void addToStack(List<NestedInteger> nestedList){ for(int i = nestedList.size()-1;i>=0;i--){ stack.add(nestedList.get(i)); } } } ```