Java solution 6ms


  • 0
    K
    public class NestedIterator implements Iterator<Integer> {
        Iterator<NestedInteger> iterator;
        NestedIterator nextIterator = null;
        Integer currInteger = null;
        public NestedIterator(List<NestedInteger> nestedList){
            iterator = nestedList.iterator();
        }
        @Override
        public boolean hasNext() {
            if((currInteger == null && nextIterator == null) || (currInteger == null && nextIterator != null && !nextIterator.hasNext())){
                nextIterator = null;
                while(iterator.hasNext()){
                    NestedInteger next = iterator.next();
                    if(next != null){
                        if(next.isInteger()){
                            currInteger = next.getInteger();
                            break;
                        }else{
                            NestedIterator nI = new NestedIterator(next.getList());
                            if(nI.hasNext()){
                                nextIterator = nI;
                                break;
                            }
                        }
                    }
                }
                return currInteger != null || nextIterator != null;
            }else{
                return true;
            }
        }
    
        @Override
        public Integer next() {
            if(hasNext()){
                if(currInteger != null){
                    int result = currInteger;
                    currInteger = null;
                    return result;
                }
                else{
                    return nextIterator.next();
                }
            }
            throw new NoSuchElementException();
        }
    }

Log in to reply
 

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