Simple Java solution working for generic types


  • 0
    M

    Most solutions I've seen do not work for generic types as they use null as a special value to indicate the end of the iterator. However, what if we wanted to iterate within possibly null values? If we want to allow null values inside the iterator we need to add an extra flag to indicate whether we are done or not.

    // Java Iterator interface reference:
    // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
    class PeekingIterator implements Iterator<Integer> {
            Integer next;
            boolean done;
            Iterator<Integer> it;
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    // initialize any member here.
    	    it = iterator;
    	    if(it.hasNext()) { 
    	        next = it.next();
    	        done = false;
    	    }else{
    	        done = true;
    	    }
    	}
    
        // Returns the next element in the iteration without advancing the iterator.
    	public Integer peek() {
            return next;
    	}
    
    	// hasNext() and next() should behave the same as in the Iterator interface.
    	// Override them if needed.
    	@Override
    	public Integer next() {
    	    Integer res = next;
    	    if(it.hasNext()) { 
    	        next = it.next();
    	    }else{
    	        done = true;
    	    }
    	    return res;
    	}
    
    	@Override
    	public boolean hasNext() {
    	    return !done;
    	}
    }
    

    I believe this solution is better on a coding interview as it works for any type (not just integers) and allows for nulls withing the values.


Log in to reply
 

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