My Java solution without setting the peeked value to null


  • 0
    L

    In my solution I have three variables which are a iterator, a integer peek value and a boolean value indicating whether the iterator is empty. The small trick here is I store the current value of the iterator in the peek value and let the iterator point to the next possible value. Since there could be no next value, using hasNext() function will not correctly checked whether the peeking iterator is empty so I use a boolean variable to help indicate whether the iterator has no next value or not. Below is my code in Java:

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

  • 0
    W

    I think there is a problem in your code: if there is no element left, peekVal should be set to null in call(), or when I keep calling next() or peek() after all the elements are iterated, it will keep showing the last element.


  • 0
    L

    Yes, you are right. If we want to set it to null we have to declare the peekValue using Integer instead of int.


Log in to reply
 

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