🌕🌕 284. 顶端迭代器

吞佛童子2022年10月10日
  • algorithm
  • Iterator
小于 1 分钟

🌕🌕 284. 顶端迭代器

难度: 🌕🌕

问题描述

img_21.png


解法

// 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 cacheNext; // 首先保存下一个元素,这样 peek 直接返回该元素,而不需要指针后移
	public PeekingIterator(Iterator<Integer> iterator) {
	    // initialize any member here.
	    this.iterator = iterator;
	}
	
    // Returns the next element in the iteration without advancing the iterator.
	public Integer peek() {
        if(cacheNext == null) {
            cacheNext = iterator.next(); // 这里 iterator 的指针已经后移了
        }
        return cacheNext;
	}
	
	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	@Override
	public Integer next() {
	    // 判断 缓存中是否存在
        if(cacheNext != null) {
            Integer res = cacheNext;
            cacheNext = null; // 清空,方便后续判断为空时,赋值时实现指针的后移
            return res;
        } else {
            // 缓存中不存在
            return iterator.next(); // 直接指针后移
        }
	}
	
	@Override
	public boolean hasNext() {
	    if(cacheNext == null) {
            return iterator.hasNext();
        } else {
            // cacheNext != null 说明后续节点肯定存在
            return true;
        }
	}
}

输出

img_20.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou