1. Do it in a normal way without iterator.
To set two variables, a pointer to the position of the list currently traversed, a pointer to the current list of elements within the position.
Hasnext () puts Eleindex and ListIndex in the position of the next available value, and returns False if no edge is available.
Next () returns the value of the two variable position.
1 Public classVector2dImplementsIterator<integer> {2 intEleindex, ListIndex;3List<list<integer>>Vec;4 5 PublicVector2d (list<list<integer>>vec2d) {6VEC =vec2d;7Eleindex = 0;8ListIndex = 0;9 }Ten One @Override A PublicInteger Next () { - returnVec.get (ListIndex). Get (eleindex++); - } the - @Override - Public BooleanHasnext () { - while(ListIndex <vec.size ()) { + if(Eleindex <Vec.get (listIndex). Size ()) { - return true; +}Else { AEleindex = 0; atlistindex++; - } - } - return false; - } -}
It is important to note that:
13 lines, after next () the value of Eleindex + +, cannot be added in Hasnext (), because in theory not every call Hashnext () must follow next ()
2. Using the Iterator method
The principle is the same as the above method, is to change the specific index to iterator
1 Public classVector2dImplementsIterator<integer> {2Iterator<list<integer>>Listit;3Iterator<integer>Eleit;4 5 PublicVector2d (list<list<integer>>vec2d) {6Listit =vec2d.iterator ();7 }8 9 @OverrideTen PublicInteger Next () { One returnEleit.next (); A } - - @Override the Public BooleanHasnext () { - while(Eleit = =NULL|| !eleit.hasnext ()) &&Listit.hasnext ()) { -Eleit =Listit.next (). iterator (); - } + returnEleit! =NULL&&Eleit.hasnext (); - } +}
It is important to note that
16 lines While is not if, because has been to find the next can be used, there is the first set of Eleit of the judgment to parentheses, or will be executed first &&, if it is the first Eleit, then Eleit will be directly assigned Listit.next () value, But it's possible to start with an empty list, where the chance goes wrong.
251. Flatten 2D Vector