Java easy understand solution


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

Log in to reply
 

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