码迷,mamicode.com
首页 > 其他好文 > 详细

284. Peeking Iterator

时间:2018-08-09 18:25:53      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:iter   res   HERE   git   pre   col   should   bsp   The   

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

标签:iter   res   HERE   git   pre   col   should   bsp   The   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9450643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!