284. Peeking Iterator

This is a Iterator problem too, the soltuion is:

1. keep a variable, nextInt, to store the potential next Integer.

2. when peek(), if the nextInt is not null, then just return it, otherwise, we must call next(), and store the next integer to nextInt.

3. When next(), if the nextInt is not null, then we need to make the nextInt to null, that means, the nextInt has been used. and then return the nextInt's value. Otherwise, return next();

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

 

上一篇:java:包装类


下一篇:Java的包装类