您的位置:首页 > 编程语言 > C语言/C++

Peeking Iterator

2016-06-21 16:35 330 查看

c++

// 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 {
private:
int m_next;
bool m_hasnext;
public:
PeekingIterator(const vector<int>& nums) : Iterator(nums) {
m_hasnext = Iterator::hasNext();
if (m_hasnext) m_next = Iterator::next();
}

int peek() {
return m_next;
}

int next() {
int t = m_next;
m_hasnext = Iterator::hasNext();
if (m_hasnext) m_next = Iterator::next();
return t;
}

bool hasNext() const {
return m_hasnext;
}
};


reference:

https://leetcode.com/discuss/61444/another-c-solution-with-one-line-in-peek-and-hasnext-ac

https://leetcode.com/discuss/59415/simple-solution-line-method-without-extra-member-variables
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言