284. Peeking Iterator (Medium)

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation -- it essentially peek() at the element that will be returned by the next call to next().

Here is an example. Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].

Call next() gets you 1, the first element in the list.

Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.

You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.

Hint:

  1. Think of "looking ahead". You want to cache the next element.
  2. Is one variable sufficient? Why or why not?
  3. Test your design with call order of peek() before next() vs next() before peek().
  4. For a clean implementation, check out Google's guava library source code.

Follow up: How would you extend your design to be generic and work with all types, not just integer?

Solution:

这道题让我们实现一个顶端迭代器,在普通的迭代器类Iterator的基础上增加了peek的功能,就是返回查看下一个值的功能,但是不移动指针,next()函数才会移动指针,那我们可以定义一个变量专门来保存下一个值,再用一个bool型变量标记是否保存了下一个值,再调用原来的一些成员函数,就可以实现这个顶端迭代器了,参见代码如下:

// Below is the interface for Iterator, which is already defined for you.
// **DO NOT** modify the interface for Iterator.
class Iterator {
    struct Data;
    Data* data;
public:
    Iterator(const vector<int>& nums);
    Iterator(const Iterator& iter);
    virtual ~Iterator();
    // Returns the next element in the iteration.
    int next();
    // Returns true if the iteration has more elements.
    bool hasNext() const;
};


class PeekingIterator : public Iterator {
public:
    PeekingIterator(const vector<int>& nums) : Iterator(nums) {
        // Initialize any member here.
        // **DO NOT** save a copy of nums and manipulate it directly.
        // You should only use the Iterator interface methods.
        flag_ = false;
    }

    // Returns the next element in the iteration without advancing the iterator.
    int peek() {
        if (!flag_) {
            val_ = Iterator::next();
            flag_ = true;
        }
        return val_;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    int next() {
        if (flag_) {
            flag_ = false;
            return val_;
        } 

        return Iterator::next();
    }

    bool hasNext() const {
        if (flag_) return true;
        return Iterator::hasNext();
    }

private:
    int val_;
    bool flag_;
};

version 2: 3ms

// Below is the interface for Iterator, which is already defined for you.
// **DO NOT** modify the interface for Iterator.
class Iterator {
    struct Data;
    Data* data;
public:
    Iterator(const vector<int>& nums);
    Iterator(const Iterator& iter);
    virtual ~Iterator();
    // Returns the next element in the iteration.
    int next();
    // Returns true if the iteration has more elements.
    bool hasNext() const;
};


class PeekingIterator : public Iterator {
public:
    PeekingIterator(const vector<int>& nums) : Iterator(nums) {
        // Initialize any member here.
        // **DO NOT** save a copy of nums and manipulate it directly.
        // You should only use the Iterator interface methods.
        hasNext_ = Iterator::hasNext();
        if (hasNext_) next_ = Iterator::next();
    }

    // Returns the next element in the iteration without advancing the iterator.
    int peek() {
        return next_;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    int next() {
        int val = next_;
        hasNext_ = Iterator::hasNext();
        if (hasNext_) next_ = Iterator::next();
        return val;
    }

    bool hasNext() const {
        return hasNext_;
    }
private:
    int next_;
    bool hasNext_;
};

results matching ""

    No results matching ""