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().

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?

这道题让我们实现一个顶端迭代器,在普通的迭代器类Iterator的基础上增加了peek的功能,就是返回查看下一个值的功能,但是不移动指针,next()函数才会移动指针,那我们可以定义一个变量专门来保存下一个值,再用一个bool型变量标记是否保存了下一个值,再调用原来的一些成员函数,就可以实现这个顶端迭代器了,参见代码如下:

解法一:

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) {
_flag = false;
} int peek() {
if (!_flag) _value = Iterator::next();
_flag = true;
return _value;
} int next() {
if (!_flag) return Iterator::next();
_flag = false;
return _value;
} bool hasNext() const {
return _flag || Iterator::hasNext();
} private:
int _value;
bool _flag;
};

这道题主要的考点就是peek函数,因为这个是默认的迭代器不具备的功能。我们其实可以使用一个小trick来实现peek功能,由于peek是要暗中观察一下下一个元素,但是迭代器并不真正移动到下一个,那么我们其实是可以创建一个副本,然后让副本移动到下一个,并返回,由于是局部变量,副本在调用结束后也会被销毁,所以并没有任何内存问题,可以说是一种相当聪明的解法了,参见代码如下:

解法二:

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) {} int peek() {
return Iterator(*this).next();
} int next() {
return Iterator::next();
} bool hasNext() const {
return Iterator::hasNext();
}
};

类似题目:

Binary Search Tree Iterator

Flatten 2D Vector

Zigzag Iterator

参考资料:

https://leetcode.com/problems/peeking-iterator/

https://leetcode.com/problems/peeking-iterator/discuss/72650/10-line-C%2B%2B-and-14-line-Java-Implementation

https://leetcode.com/problems/peeking-iterator/discuss/72554/Simple-C%2B%2B-solution-(1-line-per-method)-without-extra-member-variables

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Peeking Iterator 顶端迭代器的更多相关文章

  1. LeetCode Peeking Iterator

    原题链接在这里:https://leetcode.com/problems/peeking-iterator/ 题目: Given an Iterator class interface with m ...

  2. LeetCode——Peeking Iterator

    Description: Given an Iterator class interface with methods: next() and hasNext(), design and implem ...

  3. [Java]LeetCode284. 顶端迭代器 | Peeking Iterator

    Given an Iterator class interface with methods: next() and hasNext(), design and implement a Peeking ...

  4. Leetcode 284.顶端迭代器

    顶端迭代器 给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext().设计并实现一个支持 peek() 操作的顶端迭代器 -- 其本质就是把原本应由 next() 方法返回的元 ...

  5. Java实现 LeetCode 284 顶端迭代器

    284. 顶端迭代器 给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext().设计并实现一个支持 peek() 操作的顶端迭代器 – 其本质就是把原本应由 next() 方法 ...

  6. Java之集合初探(二)Iterator(迭代器),collections,打包/解包(装箱拆箱),泛型(Generic),comparable接口

    Iterator(迭代器) 所有实现了Collection接口的容器都有一个iterator方法, 用来返回一个实现了Iterator接口的对象 Iterator对象称作迭代器, 用来方便的实现对容器 ...

  7. Iterator接口(迭代器)

    目录 前言 原理 方法 异常 Iterator接口(迭代器) 前言 一般遍历数组都是采用for循环或者增强for,这两个方法也可以用在集合框架,但是还有一种方法是采用迭代器遍历集合框架,它是一个对象, ...

  8. STL源码分析-iterator(迭代器)

    1. GOF 迭代器设计模式 前面一篇文章有写到stl_list的实现,也实现了一下相应的iterator,但是后面觉得,实现具体容器之前有必要介绍一下iterator(迭代器) .那么迭代器是什么呢 ...

  9. Set,Multiset,Iterator(迭代器)详解

    Set,Multiset,Iterator(迭代器) Iterator:迭代器 我们可以发现所谓一些数据结构比如说数组和链表,它们都有一些相似的性质.我们看下面两个例子: 数组:定义数组\(int~a ...

随机推荐

  1. niginx代理配置

    常用关键词:rewrite.proxy_pass location ^~ /address/ { proxy_set_header Host xx.sohu.com; #设置header proxy_ ...

  2. C#6新特性,让你的代码更干净

    前言 前几天看一个朋友的博客时,看他用到了C#6的特性,而6出来这么长时间还没有正儿八经看过它,今儿专门看了下新特性,说白了也不过是语法糖而已.但是用起来确实能让你的代码更加干净些.Let's try ...

  3. 【分布式】Zookeeper数据与存储

    一.前言 前面分析了Zookeeper对请求的处理,本篇博文接着分析Zookeeper中如何对底层数据进行存储,数据存储被分为内存数据存储于磁盘数据存储. 二.数据与存储 2.1 内存数据 Zooke ...

  4. js的OOP继承实现

    以下视频截图均来自慕课网javascript深入浅出: 这里Student.prototype之所以使用create方法来创建,而不是直接赋Person.prototype的值,是因为如果使用赋值的话 ...

  5. CSS知识总结(二)

    CSS的选择符分成: 1. 通配选择符 2. 元素选择符 3. 群组选择符 4. 关系选择符 5. id及class选择符 6. 伪类选择符 7. 属性选择符 8. 伪对象选择符 1.通配选择符(*) ...

  6. iOS: 在iPhone和Apple Watch之间共享数据: App Groups

    我们可以在iPhone和Apple Watch间通过app groups来共享数据.方法如下: 首先要在dev center添加一个新的 app group: 接下来创建一个新的single view ...

  7. 基于trie树的具有联想功能的文本编辑器

    之前的软件设计与开发实践课程中,自己构思的大作业题目.做的具有核心功能,但是还欠缺边边角角的小功能和持久化数据结构,先放出来,有机会一点点改.github:https://github.com/chu ...

  8. zeroclipboard浏览器复制插件使用记录

    一个简单例子: <html> <body> <button id="copy-button" data-clipboard-text="Co ...

  9. JavaScript弹窗

    警告框: alert("警告信息!"); alert("警告\n信息!"); 确认框: var t=confirm("请确认!"); // ...

  10. Windows下删除.svn文件夹的最简易方法

    建立一个文本文件,取名为kill-svn-folders.reg(扩展名由txt改为reg),内容如下: Windows Registry Editor Version 5.00 [HKEY_LOCA ...