284. Peeking Iterator

Posted 我的名字叫周周

tags:

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

/*
 * 284. Peeking Iterator
 * 2016-6-27 by Mingyang
 * 我开始的想法是在peek的时候把next的value返回,然后copy一个iterator
 * 但是太复杂,这里只需要提前把下一个next存起来,那么每次call next的时候
 * 我们就需要把下一个的下一个再存起来
 */
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 iter.hasNext();
    //这里不能用这个,因为本题的逻辑是提前预支hasNext()并且赋值为next这个变量
        return next != null;
    }
    @Override
    public void remove() {
        // TODO Auto-generated method stub
        
    }
}

 

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

284. Peeking Iterator

284. Peeking Iterator

java 284. Peeking Iterator.java

java 284. Peeking Iterator.java

java 284. Peeking Iterator.java

java 284. Peeking Iterator.java