Ac solution code


  • 0

    There's no peak() function in the original Iterator class, that's what we need to implement. The basic idea is getting Iterator.next() one step ahead, then use it as the returned peeking value.

    JAVA Code:

    class PeekingIterator implements Iterator<Integer> {
    	private Iterator<Integer> iterator;
    	private Integer next = null;
    	public PeekingIterator(Iterator<Integer> iterator) {
    		this.iterator = iterator;
    		next = iterator.hasNext() ? iterator.next() : null;
    	    
    	}
    
    	public Integer peek() {
            return next; 
    	} 
    
    	@Override
    	public Integer next() {
    	    Integer res = next;
    	    next = iterator.hasNext() ? iterator.next() : null; 
    	    return res;
    	}
    
    	@Override
    	public boolean hasNext() {
    	    return (next != null);
    	}
    }

Log in to reply
 

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