Flatten the list and iterate with plain next() and hasNext() (Java)


  • 18
    L

    First flatten the list to a list of Integer by using DFS, then just call the plain next() and hasNext()

    public class NestedIterator implements Iterator<Integer> {
    
    private List<Integer> flattenedList;
    private Iterator<Integer> it;
    
    public NestedIterator(List<NestedInteger> nestedList) {
        flattenedList = new LinkedList<Integer>();
        flatten(nestedList);
        it = flattenedList.iterator();
    }
    
    private void flatten(List<NestedInteger> nestedList) {
        for (NestedInteger i : nestedList) {
            if (i.isInteger()) {
                flattenedList.add(i.getInteger());
            } else {
                flatten(i.getList());
            }
        }
    }
    
    @Override
    public Integer next() {
        return it.next();
    }
    
    @Override
    public boolean hasNext() {
        return it.hasNext();
    }

  • 0
    S

    Very straightforward!!


  • 0
    I

    Is it ok to give this solution during interview?


  • 0

    @lowiq I got the same thing >_< but the only difference is that i didn't keep the List<Integer> flattenedList since I already had the iterator (beats 95.44%)


  • 0
    H

    @IWantToPass said in Flatten the list and iterate with plain next() and hasNext() (Java):

    Is it ok to give this solution during interview?

    I dont think so.. Might be a good starting point,.. but I think the whole point of implementing it as an Iterator is that you dont flatten out the whole list and generate the next one as you go along..


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.