My Java solution without setting the peeked value to null

  • 0

    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:
    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 =;
        // 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.
    	public Integer next() {
    	    int result = peekVal;
    	    if(_iterator.hasNext()) peekVal =;
    	    else {
    	    return result;
    	public boolean hasNext() {
    	    return !empty;

  • 0

    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

    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.