栈-N341-扁平化嵌套列表迭代器

2019-03-31  本文已影响0人  三次元蚂蚁

题目

思路

代码

/**
 * // 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> {
    private LinkedList<NestedIntegerWrap> stack = new LinkedList<>();
    //use pre-calculate nextVal avoid nested empty list case
    private Integer nextVal;
    
    public NestedIterator(List<NestedInteger> nestedList) {
        if (nestedList != null && nestedList.size() > 0) {
            stack.push(new NestedIntegerWrap(nestedList));
        }
        //first pre-calculate nextVal when new NestedIterator
        nextVal = getNext();
    }
    
    private Integer getNext() {
        NestedIntegerWrap top;
        NestedInteger val;
        List<NestedInteger> nestedList;
        while (!stack.isEmpty()) {
            top = stack.peek();
            if (!top.hasNext()) {
                stack.pop();
            }
            val = top.getNestedInteger();
            if (val.isInteger()) {
                return val.getInteger();
            } else {
                nestedList = val.getList();
                if (nestedList != null && nestedList.size() > 0) {
                    stack.push(new NestedIntegerWrap(nestedList));
                }
            }
        }
        return null;
    }

    //pre-calculate nextVal and return tempVal
    @Override
    public Integer next() {
        Integer tempVal = nextVal;
        nextVal = getNext();
        return tempVal;
    }

    //pre-calculate nextVal is null => hasNext is null
    @Override
    public boolean hasNext() {
        return nextVal != null;
    }
    
    class NestedIntegerWrap {
        List<NestedInteger> nestedList;
        int index;
        
        NestedIntegerWrap(List<NestedInteger> nestedList) {
            this.nestedList = nestedList;
        }
        
        boolean hasNext() {
            return index < nestedList.size() - 1;
        }
        
        NestedInteger getNestedInteger() {
            return nestedList.get(index++);
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读