Simple Java solution without Stack [7ms]


  • 0
    W

    public class NestedIterator implements Iterator<Integer> {
    List<Integer> list = null;
    int currIndex = -1;

    public NestedIterator(List<NestedInteger> nestedList) {
        list = unfold(nestedList);
    }
    
    List<Integer> unfold(List<NestedInteger> nestedList) {
        List<Integer> list = new ArrayList<>();
        for (NestedInteger ni : nestedList) {
            if (ni.isInteger()) {
                list.add(ni.getInteger());
            } else {
                list.addAll(unfold(ni.getList()));
            }
        }
        return list;
    }
    
    @Override
    public Integer next() {
        return list.get(++currIndex);
    }
    
    @Override
    public boolean hasNext() {
        if (list.isEmpty()) {
            return false;
        } else {
            return (currIndex + 1) < list.size();
        }
    }
    

    }


Log in to reply
 

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