Given a nested list of integers, implement an iterator to flatten it.
Each element was 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]
.
Analysis:
We use recursive iterator. If the next element is a list, we create another iterator to traverse it. One key point here is:either there is next element or the Hasnext () function returns FALSE.
After fetch the curent element (return of Next ()), we need to move the pointer to the next element. When moving, we need to (1) determine whether there is next element; (2) Skip all empty lists.
Solution:
1 /**2 *//This is the interface, allows for creating nested lists.3 *//should not implement it, or speculate on its implementation4 * Public interface Nestedinteger {5 *6 * // @returntrue if this nestedinteger holds a single integer, rather than a nested list.7 * Public boolean isinteger ();8 *9 * // @returnThe single integer Nestedinteger holds, if it holds a single integerTen *//Return NULL if this nestedinteger holds a nested list One * Public Integer Getinteger (); A * - * // @returnthe nested list that this nestedinteger holds, if it holds a nested list - *//Return NULL if this nestedinteger holds a single integer the * Public list<nestedinteger> getList (); - * } - */ - Public classNestediteratorImplementsIterator<integer> { + -List<nestedinteger>list; + nestediterator Curiterator; A intNextindex; at Booleanisnestedlist; - BooleanHasnext; - - PublicNestediterator (list<nestedinteger>nestedlist) { -List =nestedlist; -Nextindex =-1; in MoveToNext (); - } to + @Override - PublicInteger Next () { theInteger nextval=NULL; * if(isnestedlist) { $Nextval =Curiterator.next ();Panax Notoginseng if(!Curiterator.hasnext ()) MoveToNext (); -}Else { theNextval =List.get (Nextindex). Getinteger (); + MoveToNext (); A } the returnNextval; + } - $ @Override $ Public BooleanHasnext () { - returnHasnext; - } the - Public voidMoveToNext () {Wuyi while(true){ thenextindex++; - if(nextindex>=list.size ()) { WuHasnext =false; - return; About } $ -Isnestedlist =!List.get (Nextindex). Isinteger (); - if(isnestedlist) { -Curiterator =NewNestediterator (List.get (Nextindex). GetList ()); A if(!curiterator.hasnext ())Continue; +}ElseCuriterator =NULL; theHasnext =true; - return; $ } the } the } the the /** - * Your Nestediterator object would be instantiated and called as such: in * Nestediterator i = new Nestediterator (nestedlist); the * while (I.hasnext ()) v[f ()] = I.next (); the */
Leetcode-flatten Nested List Iterator