284. Peeking Iterator

题目描述和难度

  • 题目描述:

给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext()。设计并实现一个支持 peek() 操作的顶端迭代器 -- 其本质就是把原本应由 next() 方法返回的元素 peek() 出来。

示例:

假设迭代器被初始化为列表 [1,2,3]。

调用 next()返回 1,得到列表中的第一个元素。
现在调用 peek() 返回 2,下一个元素。在此之后调用 next() 仍然返回 2。
最后一次调用 next() 返回 3,末尾元素。在此之后调用 hasNext() 应该返回 false

进阶:你将如何拓展你的设计?使之变得通用化,从而适应所有的类型,而不只是整数型?

思路分析

求解关键:

参考解答

参考解答1

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {

    private Iterator<Integer> iterator;

    private Integer peek = null;

    private boolean peeked = false;

    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 (peeked) {
            return peek;
        } else {
            peeked = true;
            peek = iterator.next();
        }
        return peek;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        if (peeked) {
            peeked = false;
            return peek;
        } else {
            return iterator.next();
        }
    }

    @Override
    public boolean hasNext() {
        return peeked || iterator.hasNext();
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        Iterator<Integer> iterator = list.iterator();
        PeekingIterator peekingIterator = new PeekingIterator(iterator);
        Integer peek1 = peekingIterator.peek();
        System.out.println(peek1);

        Integer peek2 = peekingIterator.peek();
        System.out.println(peek2);

        Integer peek3 = peekingIterator.peek();
        System.out.println(peek3);

        Integer peek4 = peekingIterator.peek();
        System.out.println(peek4);

        Integer next1 = peekingIterator.next();
        System.out.println(next1);

        Integer peek5 = peekingIterator.peek();
        System.out.println(peek5);

        Integer next2 = peekingIterator.next();
        System.out.println(next2);
        Integer next3 = peekingIterator.next();
        System.out.println(next3);
    }
}

本篇文章的地址为 https://liweiwei1419.github.io/leetcode-solution/leetcode-0284-peeking-iterator ,如果我的题解有错误,或者您有更好的解法,欢迎您告诉我 liweiwei1419@gmail.com