Clear short solution with Java


  • 0
    J
    public class NestedIterator implements Iterator<Integer> {
        
        private Deque<List<NestedInteger>> stackList = new LinkedList<>();
        private Deque<Integer> stackIndex = new LinkedList<>();
        private List<NestedInteger> list;
        private int i;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            list = nestedList;
            i = 0;
            moveToValid();
        }
    
        @Override
        public Integer next() {
            Integer res = list.get(i).getInteger();
            i++;
            moveToValid();
            return res;
        }
    
        @Override
        public boolean hasNext() {
            return i < list.size();
        }
    
        private void moveToValid() {
            while (true) {
                if (i < list.size()) {
                    if (list.get(i).isInteger()) break;
                    else {
                        List<NestedInteger> nextList = list.get(i).getList();
                        stackList.push(list);
                        stackIndex.push(i);
                        list = nextList;
                        i = 0;
                    }
                }
                else if (stackList.isEmpty()) break;
                else {
                    list = stackList.pop();
                    i = stackIndex.pop() + 1;
                }
            }        
        }
    }

Log in to reply
 

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