I think null can be a Integer value in java.


  • 0
    G

    // Java Iterator interface reference:
    // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
    class PeekingIterator implements Iterator<Integer> {

    Iterator<Integer> iterator;
    
    Integer mid = null;
    boolean hasNext = false;
    
    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        this.iterator = iterator;
        if (iterator.hasNext()) {
            mid = iterator.next();
            hasNext = true;
        }
    }
    
    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        return mid;
    }
    
    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        Integer re = mid;
        if (iterator.hasNext()) {
            mid = iterator.next();
            hasNext = true;
        } else {
            mid = null;
            hasNext = false;
        }
        return re;
    }
    
    @Override
    public boolean hasNext() {
        if (mid == null && hasNext == false) {
            return false;
        } else {
            return true;
        }
    }
    

    }


Log in to reply
 

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