码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Peeking Iterator"

时间:2015-09-21 17:12:45      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
class PeekingIterator : public Iterator {
    bool bPeeked;
    int val;
public:
    PeekingIterator(const vector<int>& nums) : Iterator(nums) {
        val = -1;
        bPeeked = false;
    }

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

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

    bool hasNext() const {
        return bPeeked || Iterator::hasNext();
    }
};
View Code

LeetCode "Peeking Iterator"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4826322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!