2 Java solutions,


  • 0
    M
    1. Flatten first.
    public class NestedIterator implements Iterator<Integer> {
        List<Integer> list;
        Iterator<Integer> iter;
        public NestedIterator(List<NestedInteger> nestedList) {
            list = new ArrayList<>();
            flatten(nestedList);
            iter = list.iterator();
        }
        
        private void flatten(List<NestedInteger> nestedList){
            for(NestedInteger nestedInt : nestedList){
                if(nestedInt.isInteger()){
                    list.add(nestedInt.getInteger());
                } else {
                    flatten(nestedInt.getList());
                }
            }
        }
    
        @Override
        public Integer next() {
            return iter.next();
        }
    
        @Override
        public boolean hasNext() {
            return iter.hasNext();
        }
    }
    
    1. Use stack.
    public class NestedIterator implements Iterator<Integer> {
        Stack<NestedInteger> stack;
        public NestedIterator(List<NestedInteger> nestedList) {
            stack = new Stack<>();
            Collections.reverse(nestedList);
            for(NestedInteger nestedInt : nestedList){
                stack.push(nestedInt);
            }
        }
    
        @Override
        public Integer next() {
            return stack.pop().getInteger();
        }
    
        @Override
        public boolean hasNext() {
            while(!stack.isEmpty()){
                if(stack.peek().isInteger()){
                    return true;
                } else {
                    NestedInteger nestInt = stack.pop();
                    List<NestedInteger> nestList = nestInt.getList();
                    Collections.reverse(nestList);
                    for(NestedInteger ele : nestList){
                        stack.push(ele);
                    }                
                }
            }
            return false;
        }
    }
    

Log in to reply
 

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