Simple Java solution by caching next element


  • 13
    Z

    quite straight forward solution by caching the next element and handling hasNext() and next() by using cached entry.

    class PeekingIterator implements Iterator<Integer> {
        Integer cache = null;
        Iterator<Integer> it;
        
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    // initialize any member here.
    	    this.it = iterator;
    	    cache = it.next();
    	}
    
        // Returns the next element in the iteration without advancing the iterator.
    	public Integer peek() {
            return cache;
    	}
    
    	// hasNext() and next() should behave the same as in the Iterator interface.
    	// Override them if needed.
    	@Override
    	public Integer next() {
    	    int ret = cache;
    	    if(it.hasNext()){
    	        cache = it.next();
    	    }
    	    else{
    	        cache = null;
    	    }
    	    return ret;
    	}
    
    	@Override
    	public boolean hasNext() {
    	    return (cache != null);
    	}
    }

  • 0

    I think next() on the last element should throw NoSuchElementException instead of returning null if the same behavior is needed...


  • 0
    Y

    hi, @zahid2 , i think " cache = it.next();" in the constructor is buggy, since it.hasNext() may be false. And when we are constructing the iterator, we are not checking with hasNext() yet


Log in to reply
 

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