Share my Easy & Clean Java Code with one more preFetch boolean variance


  • 0
    Z
    class PeekingIterator implements Iterator<Integer> {
    
    private Iterator<Integer> iter;
    private Integer curr = null;
    private boolean preFetch = false;
    
    public PeekingIterator(Iterator<Integer> iterator) {
        iter = iterator;
    }
    
    public Integer peek() {
        if(!preFetch){
            curr = iter.next();
            preFetch = true;
        }
        return curr;
    }
    
    public Integer next() {
        if(preFetch){
            preFetch = false;
        } else {
            curr = iter.next();
        }
        return curr;
    }
    
    @Override
    public boolean hasNext() {
        return preFetch ? true : iter.hasNext(); 
    }

Log in to reply
 

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