Real iterator solution, not use stack


  • 0
    Q
    public class NestedIterator implements Iterator<Integer> {
    
    List<NestedInteger> nestedList;
    int i = 0;
    int max = 0;
    boolean inList = false;
    NestedIterator ite;
    public NestedIterator(List<NestedInteger> nestedList) {
        this.nestedList = nestedList;
        i = 0;
        this.max = nestedList.size();
    }
    
    @Override
    public Integer next() {
        NestedInteger tmp = nestedList.get(i);
        if(tmp.isInteger()) {i++;return tmp.getInteger();}
        else{
            
            if(!inList){
                List<NestedInteger> other = tmp.getList();
                ite = new NestedIterator(other);
                inList = true;
            }
            
            if(ite.hasNext()) return ite.next();
            else{
                inList = false;
                i++;
                return next();
            }
            
        }
    }
    
    @Override
    public boolean hasNext() {
        if(inList){
            if(ite.hasNext()) return true;
            else {
                if(i+1 == max) return false;
                else{
                    if(nestedList.get(i+1).isInteger()) return true;
                    else{
                        if(new NestedIterator(nestedList.get(i+1).getList()).hasNext()) return true;
                        else{
                            i++;
                            return hasNext();
                        }
                    }
                }
            }
        }
        //else return i != max;
        if(i == max) return false;
        if(nestedList.get(i).isInteger()) return true;
        else{
            if(new NestedIterator(nestedList.get(i).getList()).hasNext()) return true;
            else{
                i++;
                return hasNext();
            }
        }
    }
    

    }

    /**

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

Log in to reply
 

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