Share Java Solution


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

Log in to reply
 

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