284. Peeking Iterator

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了284. Peeking Iterator相关的知识,希望对你有一定的参考价值。

284. Peeking Iterator


1234
peek 1
next 1
peek 2
peek 2 
peek 2
next 2
peek 3 
next 3 
class PeekingIterator implements Iterator<Integer> {  
    private Integer next = null;
    private Iterator<Integer> iter;

    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        iter = iterator;
        if (iter.hasNext())
            next = iter.next();
    }
    
    // Returns the next element in the iteration without advancing the iterator. 
    public Integer peek() {
        return next; 
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        Integer res = next;
        next = iter.hasNext() ? iter.next() : null;
        return res; 
    }

    @Override
    public boolean hasNext() {
        return next != null;
    }
}
cache the next element. If next is null, there is no more elements in iterator.

 

以上是关于284. Peeking Iterator的主要内容,如果未能解决你的问题,请参考以下文章