A simple solution in Java with brief explanation


  • 0
    J

    The idea is straightforward: after performing a peek, cache the next element; otherwise, behave like a usual iterator.

    class PeekingIterator implements Iterator<Integer> {
        
        Iterator<Integer> iter;
        Integer curr = null;
    
    	public PeekingIterator(Iterator<Integer> iterator){
    	    iter = iterator;
    	}
    
    	public Integer peek() {
            if (curr == null) 
                curr = iter.next();
            return curr;
    	}
    
    	public Integer next() {
    	    if (curr == null) 
    	        return iter.next();
            int tmp = curr;
    	    curr = null;
    	    return tmp;    	    
    	}
    
    	public boolean hasNext() {
    	    return curr == null? iter.hasNext(): true;
    	}
    }

Log in to reply
 

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