Simple java code, hope this can help


  • 0
        public class NestedIterator implements Iterator<Integer> {
    
             List<Integer> res = new ArrayList<>();
             int index = 0;
    
         public NestedIterator(List<NestedInteger> nestedList) {
                  res = helper(nestedList);
           }
    
         private  List<Integer> helper(List<NestedInteger> list){
                    List<Integer> cur = new ArrayList<>();
                    for(NestedInteger x: list){
                           if(x.isInteger()) cur.add(x.getInteger());
                           else{
                                  List<Integer> remain = helper(x.getList());
                                  cur.addAll(remain);
                           }
                   }
                 return cur;
          }
          @Override
          public Integer next() {
                  if(this.hasNext())
                         return res.get(index++);
                 else return -1;
          }
    
          @Override
         public boolean hasNext() {
                   return index < res.size();
         }
    

    }


Log in to reply
 

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