Simplest and self-explanation Double Iterator answer, able to be applied to any similar problem.


  • 0
    L

    For all these iterator problem, the key point is to implement your fancy part in hasNext() function, and leave next() free. Call hasNext() first whenever you want to use next(), which guarantees a safe code.

    public class Vector2D implements Iterator<Integer> {
        private Iterator<List<Integer>> listIter;
        private Iterator<Integer> iter;
        public Vector2D(List<List<Integer>> vec2d) {
            iter = null;
            listIter = vec2d.iterator();
        }
    
        @Override
        public Integer next() {
            if (hasNext()){
                return iter.next();
            }
            
            return null;
        }
    
        @Override
        public boolean hasNext() {
            if (iter != null && iter.hasNext()){
                return true;
            }
            
            if (listIter == null || !listIter.hasNext()){
                return false;
            }
            iter = listIter.next().iterator();
            
            return hasNext();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.