Peeking Iterator


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?

这段话总结来说就是让我们利用next()和hasNext()实现一个peek()关键是要在派生类中设置2个数据,一个记录上一次是否调用next()的tag变量,另一个记录暂存的值,因为我们在调用peek()的时候可能让迭代器向前走一位,如果向前走了一位,则要记录这个值,比较我们当调用了一次peek()后再调用next()时,返回的是这个暂存的值。如果连续调用两次peek()我们也要返回这个暂存的值

下面是代码的实现:

// Below is the interface for Iterator, which is already defined for you.
// **DO NOT** modify the interface for Iterator.

// 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.
        tag = true;
    }

    // Returns the next element in the iteration without advancing the iterator.
    int peek() {
        if (tag) {          //如果为tag为真,说明并没有调用过Iterator::next()
            cache = Iterator::next();
            tag = false;
        }
        return cache;      //如果tag为假,说明上次调用的也少peek(),但是Iterator并未后移,直接返回cache
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    int next() {
        if (!tag) {           //如果tag为假说明调用了peek()并在其中调用了Iterator::next()
            tag = true;       
            return cache;     //直接返回cache
        }
        else
        {
            cache = Iterator::next();//如果tag为真这调用Iterator::next()
        }
        return cache;
    }

    bool hasNext() const {
        if (tag)return Iterator::hasNext();//如果tag是真说明上一次调用的是next()或者未调用,我们只需调用Iterator的hasNext()即可
        else return true;                  //如果是tag是假说明上一次调用的是peek()则一定存在下一个iterator
    }
private:
    int cache;       //暂存数据
    bool tag;        //标志
};
原文地址:https://www.cnblogs.com/csudanli/p/4963656.html