1414 * or other lists. Implement an iterator to flatten it.
1515 *
1616 * Implement the NestedIterator class:
17- * NestedIterator(List< NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.
17+ * NestedIterator(List< NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.
1818 * int next() Returns the next integer in the nested list.
1919 * boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.
2020 *
2929 * If res matches the expected flattened list, then your code will be judged as correct.
3030 *
3131 * Example 1:
32- * Input: nestedList = [[1,1],2,[1,1]]
33- * Output: [1,1,2,1,1]
34- * Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
32+ * Input: nestedList = [[1,1],2,[1,1]]
33+ * Output: [1,1,2,1,1]
34+ * Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
3535 *
3636 * Example 2:
37- * Input: nestedList = [1,[4,[6]]]
38- * Output: [1,4,6]
39- * Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
37+ * Input: nestedList = [1,[4,[6]]]
38+ * Output: [1,4,6]
39+ * Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
4040 * </pre>
41+ *
42+ * @see <a href="https://youtu.be/RiJ7Rc98vkI">Video solution</a>
4143 */
4244public class NestedIterator implements Iterator <Integer > {
4345
@@ -76,11 +78,11 @@ private Integer determineNextElement() {
7678 while (!stack .isEmpty ()) {
7779 Iterator <INestedInteger > iterator = stack .peek ();
7880 if (iterator .hasNext ()) {
79- var next = iterator .next ();
81+ INestedInteger next = iterator .next ();
8082
81- if (next .isInteger ()) {
83+ if (next .isInteger ()) { // is integer
8284 return next .getInteger ();
83- } else {
85+ } else { // is list
8486 stack .push (next .getList ().iterator ());
8587 return determineNextElement ();
8688 }
@@ -91,6 +93,9 @@ private Integer determineNextElement() {
9193 return null ;
9294 }
9395
96+ /**
97+ * This is the interface that allows for creating nested lists. You should not implement it, or speculate about its implementation
98+ */
9499 public interface INestedInteger {
95100
96101 // @return true if this NestedInteger holds a single integer, rather than a nested list.
0 commit comments