284. Peeking Iterator
2016-07-19 16:30
337 查看
Given an Iterator class interface with methods:
Here is an example. Assume that the iterator is initialized to the beginning of the list:
Call
Now you call
You call
Follow up: How would you extend your design to be generic and work with all types, not just integer?
Credits:
Special thanks to
@porker2008 for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
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.
Follow up: How would you extend your design to be generic and work with all types, not just integer?
Credits:
Special thanks to
@porker2008 for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
// 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 n; // int m; int len; 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. n=0; len=nums.size(); } // Returns the next element in the iteration without advancing the iterator. int peek() { return Iterator(*this).next(); } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. int next() { return Iterator::next(); } bool hasNext() const { return Iterator::hasNext(); } };
相关文章推荐
- Particle designer 粒子工具中属性对应功能的简单介绍
- 加载jpg图片
- listView点击条目跳转并带参数
- UE4异步载入资源
- 07.19 Linux命令 cd
- ffmpeg-20160718-git-bin.7z
- TI IPNC_RDK_V3.8.0开发环境建立步骤备忘
- 从IT人士到IT经理倪应该学会的30 项技能
- jsp中导入js文件问题
- CSS3渐变色彩
- deep learning 入门资料
- delphi firebird backup path
- Zygote 启动流程分析
- poj1068
- objective 动画
- MySQL存储引擎之Myisam和Innodb总结性梳理
- mac 安装mysql + 修改root用户密码 + 及报Access denied for user 'root'@'localhost' (using password:YES)解决办法
- python mongodb MapReduce
- 【BZOJ1103】[POI2007]大都市meg
- Maven入门指南(二)