Java solution which could work with any types and work when there is null element in collection.


  • 2
    L

    When you need to work with other type, just replace Integer with your type.

    class PeekingIterator implements Iterator<Integer> {
    
        private Integer peekElement = null;
        private Iterator<Integer> iter = null;
        private boolean hasNext = true;
        
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    iter = iterator;
            if(iterator.hasNext()) {    	        
    	        peekElement = iter.next();
    	    }
    	    else hasNext = false;
    	}
    
    	public Integer peek() {
            return peekElement;
    	}
    
    	public Integer next() {
            if(!this.hasNext()) return null; //without this line still got AC, I just think it's a proper way.
    	    Integer tmp = peekElement;
    	    if(!iter.hasNext()) {
    	        peekElement = null;
    	        hasNext = false;
    	    }
    	    else peekElement = iter.next();
    	    return tmp;
    	}
    
    	public boolean hasNext() {
    	    return hasNext;
    	}
    }

  • 0
    H

    Sorry I'm a little confusing that the peekElement will be the returned tmp from next() {}, but the tmp was null from "Integer tmp = peekElement" because peekElement was initialed as null, so in my mind the peekElement will still be null.. Could you finger out where I missed?


  • 0
    L

    Hi @haoyu2, in my constructor function, peekElement would be initialized as the first element of the input iterator if it is not empty.

    public PeekingIterator(Iterator<Integer> iterator) {
            iter = iterator;
            if(iterator.hasNext()) {                
                peekElement = iter.next();
            }
            else hasNext = false;
        }
    

Log in to reply
 

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