Java implementation LeetCode 341 flatten nested list iterators

341. flattening nested list iterators

Nested give you a list of integers. You design an iterator, so that it can traverse all the integer integer list.

Or each is an integer, or another list in the list. Where the elements of the list may be an integer or other lists.

Example 1:

Input: [[1,1], 2, [1,1]]
Output: [1,1,2,1,1]
Explanation: by repeatedly calling the next until hasNext returns false, the next order of the elements should be returned: [1,1,2,1,1].
Example 2:

Input: [1, [4, [6]]]
Output: [1,4,6]
Explanation: by repeatedly calling the next until hasNext returns false, the next order of the elements should be returned: [1,4,6].

/**
 * // 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 List<Integer> list = new ArrayList<>();
    private int index;

    private void add(List<NestedInteger> nestedList) {
        for (NestedInteger nestedInteger : nestedList) {
            if (nestedInteger.isInteger()) {
                list.add(nestedInteger.getInteger());
            } else {
                add(nestedInteger.getList());
            }
        }
    }

    public NestedIterator(List<NestedInteger> nestedList) {
        add(nestedList);
    }

    @Override
    public Integer next() {
        return list.get(index++);
    }

    @Override
    public boolean hasNext() {
        return index < list.size();
    }
}

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i = new NestedIterator(nestedList);
 * while (i.hasNext()) v[f()] = i.next();
 */
Released 1452 original articles · won praise 10000 + · views 1.73 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104738100