(LC) 341. Iterador de lista anidada aplanada

341. Acoplamiento de iteradores de listas anidadas

Darle una lista anidada de números enteros. Diseñe un iterador para que pueda atravesar todos los enteros en esta lista de enteros.

Cada elemento de la lista es un número entero u otra lista. Los elementos de la lista también pueden ser números enteros u otras listas.

Ejemplo 1:

Entrada: [[1,1], 2, [1,1]]
Salida: [1,1,2,1,1]
Explicación: Al llamar repetidamente a next hasta que hasNext devuelva falso, el orden de los elementos devueltos por next debería ser: [1,1,2,1,1].
Ejemplo 2:

Entrada: [1, [4, [6]]]
Salida: [1,4,6]
Explicación: Al llamar repetidamente a next hasta que hasNext devuelva falso, el orden de los elementos devueltos por next debería ser: [1,4,6 ].

En primer lugar, debe comprender que debajo de dfs está el recorrido de dfs

Inserte la descripción de la imagen aquí

/**
 * // 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> vals; // 用于存储新的数组
    private Iterator<Integer> cur;

    public NestedIterator(List<NestedInteger> nestedList) {
    
    
        vals = new ArrayList<Integer>(); // 初始化数组
        dfs(nestedList); // 深度遍历
        cur = vals.iterator(); // 迭代器
    }

    @Override
    public Integer next() {
    
    
        return cur.next();
    }

    @Override
    public boolean hasNext() {
    
    
        return cur.hasNext();
    }
    private void dfs(List<NestedInteger> nestedList) {
    
    
        for (NestedInteger nest:nestedList) {
    
    
            if (nest.isInteger()) {
    
     // 如果是一个单整数 则存放在vals中
                vals.add(nest.getInteger());
            } else {
    
    
                dfs(nest.getList()); 
            }
        }
    }
}

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i = new NestedIterator(nestedList);
 * while (i.hasNext()) v[f()] = i.next();
 */

Supongo que te gusta

Origin blog.csdn.net/weixin_45567738/article/details/115127678
Recomendado
Clasificación