package com.fishercoder.solutions;

import com.fishercoder.common.classes.NestedInteger;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 341. Flatten Nested List Iterator
 *
 * Given a nested list of integers, implement an iterator to flatten it.

 Each element is either an integer, or a list -- whose elements may also be integers or other lists.

 Example 1:
 Given the list [[1,1],2,[1,1]],

 By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

 Example 2:
 Given the list [1,[4,[6]]],

 By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
 */
public class _341 {

    public static class NestedIterator implements Iterator<Integer> {

        private Queue<Integer> flattenedList;
        private Iterator<Integer> iterator;

        public NestedIterator(List<NestedInteger> nestedList) {
            flattenedList = new LinkedList<>();
            constructList(nestedList);
            iterator = flattenedList.iterator();
        }

        private void constructList(List<NestedInteger> nestedList) {
            for (NestedInteger nestedInteger : nestedList) {
                if (nestedInteger.isInteger()) {
                    flattenedList.add(nestedInteger.getInteger());
                } else {
                    constructList(nestedInteger.getList());
                }
            }
        }

        @Override
        public Integer next() {
            return iterator.next();
        }

        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }
    }

}
@@ -304,17 +304,18 @@
 ten it.%0A
-%0A
+ *
  Each el
@@ -407,17 +407,21 @@
  lists.%0A
-%0A
+ *%0A *
  Example
@@ -424,16 +424,18 @@
 mple 1:%0A
+ *
  Given t
@@ -455,25 +455,26 @@
 %5D,2,%5B1,1%5D%5D,%0A
-%0A
+ *
  By calling 
@@ -581,17 +581,21 @@
 2,1,1%5D.%0A
-%0A
+ *%0A *
  Example
@@ -598,16 +598,18 @@
 mple 2:%0A
+ *
  Given t
@@ -629,17 +629,18 @@
 ,%5B6%5D%5D%5D,%0A
-%0A
+ *
  By call
@@ -892,52 +892,8 @@
 ist;
-%0A        private Iterator%3CInteger%3E iterator;
 %0A%0A  
@@ -1045,57 +1045,8 @@
 t);%0A
-            iterator = flattenedList.iterator();%0A
     
@@ -1499,21 +1499,26 @@
 urn 
-iterator.next
+flattenedList.poll
 ();%0A
@@ -1604,24 +1604,30 @@
 urn 
-iterator.hasNext
+!flattenedList.isEmpty
 ();%0A

refactor 341