博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode OJ:Peeking Iterator(peeking 迭代器)
阅读量:6614 次
发布时间:2019-06-24

本文共 2122 字,大约阅读时间需要 7 分钟。

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.

Peeking迭代器,题目不再赘述,代码如下:

1 // Below is the interface for Iterator, which is already defined for you. 2 // **DO NOT** modify the interface for Iterator. 3 class Iterator { 4     struct Data; 5     Data* data; 6 public: 7     Iterator(const vector
& nums); 8 Iterator(const Iterator& iter); 9 virtual ~Iterator();10 // Returns the next element in the iteration.11 int next();12 // Returns true if the iteration has more elements.13 bool hasNext() const;14 };15 16 17 class PeekingIterator : public Iterator {18 public:19 PeekingIterator(const vector
& nums) : Iterator(nums) {20 // Initialize any member here.21 // **DO NOT** save a copy of nums and manipulate it directly.22 // You should only use the Iterator interface methods.23 this->next();24 }25 26 // Returns the next element in the iteration without advancing the iterator.27 int peek() {28 return nextVal;29 }30 31 // hasNext() and next() should behave the same as in the Iterator interface.32 // Override them if needed.33 int next() {34 int ret = nextVal;35 if(Iterator::hasNext()){36 bNext = true;37 nextVal = Iterator::next();38 }else{39 bNext = false;40 }41 return ret;42 }43 44 bool hasNext() const {45 return bNext;46 }47 private:48 bool bNext;49 int nextVal;50 };

 

转载于:https://www.cnblogs.com/-wang-cheng/p/5014552.html

你可能感兴趣的文章
Tensorflow在win10下的安装(CPU版本)
查看>>
嵌入式平台做深度学习算法,不可不重视的4件事
查看>>
一次优化记录
查看>>
如何调用一个数据完整的firefox浏览器
查看>>
cgroup代码浅析(2)
查看>>
会计的思考(42):会计如何转变为公司的内部财务顾问
查看>>
利用钥匙串,在应用里保存用户密码的方法
查看>>
final,finally和finalize之间的区别
查看>>
python 装饰器
查看>>
[辟谣]下蹲猛起来眼前发黑是心脏衰竭的表现?别扯了!
查看>>
paper 96:计算机视觉-机器学习近年部分综述
查看>>
vuex状态管理详细使用方法
查看>>
不要等有了足够的钱才选择去创业!!!
查看>>
手把手教你画嘴巴,以后再也不怕画嘴巴了
查看>>
selenium - webdriver - 截图方法get_screenshot_as_file()
查看>>
linux 命令 — archive
查看>>
强大的jQuery网格插件 ParamQuery
查看>>
io.lettuce.core.RedisCommandTimeoutException: Command timed out
查看>>
种子填充算法描述及C++代码实现
查看>>
Kali渗透测试——快速查找Metasploit的模块
查看>>