My simple Java solution


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

    Approach is, use the passed iterator in constructor.
    Have a field which points to current element, in order for peek() to work.
    When ever peek is called, first check the field and if not empty return that. Otherwise, get the next element from parent iterator and store in it.
    Accordingly while accessing hasNext() and next() methods, consider the value of field before passing to parent iterator.


Log in to reply
 

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