Problem 284

Posted by Ruizhi Ma on October 31, 2020

Solution URL

https://leetcode.com/submissions/detail/415269877/

代码

// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

import java.util.NoSuchElementException;

class PeekingIterator implements Iterator<Integer> {
    private Iterator<Integer> it;
    private Integer peekValue;

	public PeekingIterator(Iterator<Integer> iterator) {
	    // initialize any member here.
        it = iterator;
        peekValue = null;

	}

    // Returns the next element in the iteration without advancing the iterator.
	public Integer peek() {
        //check whether it has next or not
        if(peekValue == null){
            //check is there a next value or not
            while(!it.hasNext()){
                throw new NoSuchElementException();
            }
            //it has next, so can invocate next function
            peekValue = it.next();
        }
        return peekValue;
	}

	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	@Override
	public Integer next() {
	    //check peekValue has value or not; if has, then that is the next value
        //or invocate next function
        if(peekValue != null){
            int returnValue = peekValue;
            peekValue = null;//it must be reset here!
            return returnValue;
        }

        return it.next();
	}

	@Override
	public boolean hasNext() {
	    return peekValue != null || it.hasNext();
	}
}