二刷341. Flatten Nested List Iterator

Medium
hasNext()很容易出错,基本上这道题flatten的操作都是在hasNext()这里完成的。我们peek()一下去看下一个要从stack里取出来的是integer还是list. 如果是integer, 那么ok没问题hasNext()return true, 而且next()直接return stack.pop.getInteger()就没事; 如果是list,说明这一坨需要flatten. 那么我们先把这一坨pop()出来,再从后到前遍历这个list加到stack里。到这里发现我们这样做不能循环call下去,只是把list转了个方向往stack里加了一下。所以我们要写一个while loop, 知道能flatten出一个integer为止;
比如[1,2,[3,[4]]]这个NestedList, 一开始我们加到stack里面是[[3,[4]], 2, 1], 然后我们call hasNext()的时候, stack.peek() = 1, 是integer, 所以直接返回true; 然后我们pop()掉1, call掉next()之后我们stack变成[[3,[4]], 2];这时候再call hasNext(), stack.peek()会得到2, ok没问题跟1时的操作类似,最后返回true, call一下next()我们再次得到stack = [[3,[4]]], 这这时候call hasNext()的时候就会导致stack.pop(), 然后得到一个list = [3,[4]], 从后到前push到stack里得到[[4], 3],peek()一下得到3是integer所以返回true.再call next()使得3被pop()出来,stack里面还剩[[4]], 这时候call peek得到的是list, 所以会pop出来得到list = [4], 这时候把4加到stack里面,得到stack = [4](which is different from stack = [[4]]),所以再call hasNext()的时候会检测到ni.isInteger()然后直接返回true.

/**
 * // 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 List<NestedInteger> getList();
 * }
 */
public 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 ni = stack.peek();
            if (ni.isInteger()){
                return true;
            }
            stack.pop();
            List<NestedInteger> list = ni.getList();
            for(int i = list.size() - 1; i >= 0; i--){
                stack.push(list.get(i));
            }
        }
        return false;
    }
}

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i = new NestedIterator(nestedList);
 * while (i.hasNext()) v[f()] = i.next();
 */
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/3492c3fc356c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞