Problem

Implement an iterator to flatten a 2d vector.

Example:

Input: 2d vector =
[
  [1,2],
  [3],
  [4,5,6]
]
Output: [1,2,3,4,5,6]
Explanation: By calling next repeatedly until hasNext returns false, 
             the order of elements returned by next should be: [1,2,3,4,5,6].

Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

Solution

public class Vector2D implements Iterator<Integer> {
    private Iterator<List<Integer>> rows;
    private Iterator<Integer> row;
    
    public Vector2D(List<List<Integer>> vec2d) {
        rows = vec2d.iterator();
    }

    public Integer next() {
        if (hasNext()) return row.next();
        else return null;
        
    }

    //hasNext() is actually moving row iterator to next row 
    //when it's null or reached the end of current row
    public boolean hasNext() {
        while ((row == null || !row.hasNext()) && rows.hasNext()) {
            row = rows.next().iterator();
        }
        return row != null && row.hasNext();
    }
}

linspiration
161 声望53 粉丝