# 284 Peeking Iterator

寫一個class PeekingIterator, implement Iterator interface, 並加上peek() function。已知Iterator interface有next()和hasNext()。

這題是我2017年google面掛的類似題。 http://www.1point3acres.com/bbs/thread-236019-1-1.html

題目提供class結構:

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

    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.

    }

    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {

    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {

    }

    @Override
    public boolean hasNext() {

    }
}

Idea 首先constructor拿到Iterator後,勢必要存到class裡,所以必須為此class宣告一個member variable: Iterator itr。Iterator的特性是呼叫next後,iterator移動到下一個element,並return原element的值,在constructor第一次呼叫next之後會回傳第一個element的值,並移動到第二個element上面。

因此可以在constructor中呼叫next,並把值存在member variable Integer val中。val就是最新的值。

peek直接回傳val

呼叫next時,要把舊val回傳,並且更新val

hasNext 如果val==null,那就沒有然後了。

Code

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

    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        this.itr = iterator;
        if(itr.hasNext())
            val = itr.next();
    }

    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        return val;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        Integer next = val;
        if(itr.hasNext()){
            val = itr.next();
        }else{
            val = null;
        }

        return next;
    }

    @Override
    public boolean hasNext() {
        return val != null;
    }
}

results matching ""

    No results matching ""