Share My 14ms Recursive Solution , Wish do make some sense


  • 0
    C

    public class NestedIterator implements Iterator<Integer> {

      LinkedList<NestedInteger> list = new LinkedList<>();
      public NestedIterator(List<NestedInteger> nestedList) {
        list.addAll(nestedList);
      }
    
      @Override
      public Integer next() {
        return list.removeFirst().getInteger();
      }
    
      @Override
      public boolean hasNext() {
        if (list.isEmpty()) {
            return false;
        }
        NestedInteger first = list.removeFirst();
        if (first.isInteger()) {
            list.addFirst(first);
            return true;
        } else {
            List<NestedInteger> temp = first.getList();
            for (int i = temp.size() - 1; i >= 0; i--) {
                list.addFirst(temp.get(i));
            }
            return hasNext();
        }
      }
    

    }


Log in to reply
 

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