My Java AC Solution

  • 0
    public class NestedIterator implements Iterator<Integer> {
        NestedIterator nextNested; //if it is nested list
        Iterator<NestedInteger> iter;
        Integer next;
        public NestedIterator(List<NestedInteger> nestedList) {
            iter = nestedList.iterator();
            next = nextR(); //get next and save it to next;
        public Integer nextR() {
                if(nextNested.hasNext()){  //nested still has more
                } else {
                    nextNested = null;  ///otherwise set it to null
            if(!iter.hasNext()) return null;
            while(iter.hasNext())  //this will handle empty nestedlist in a row like [[],[]]
                NestedInteger ni =;
                if(ni.isInteger()) return ni.getInteger();
                nextNested=new NestedIterator(ni.getList());
                Integer re=;
                if(re!=null) return re;
            return null;
        public Integer next() {
            if(next==null) return null;
            int n = next;
            next = nextR();
            return n;
        public boolean hasNext() {
            return next!=null;

Log in to reply

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