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. ASP.NET Core 中文文档 第三章 原理(15)请求功能

    作者:Steve Smith 翻译:谢炀(kiler398) 校对:姚阿勇(Dr.Yao).孟帅洋(书缘) 涉及到如何处理 HTTP 请求以及响应的独立 Web 服务器功能已经被分解成独立的接口,这些 ...

  2. Eclipse 实用技巧

    代码智能提示 Java智能提示 Window -> Preferences -> Java -> Editor -> Content Assist -> Auto Act ...

  3. [JSP]自定义标签库taglib

    自定义标签的步骤 自定义标签的步骤大概有三步: 1.继承javax.servlet.jsp.tagext.*下提供的几个标签类,如Tag.TagSupport.BodyTagSupport.Simpl ...

  4. laravel安装

    简单概括:Laravel是一套简洁.优雅的PHP Web开发框架(PHP Web Framework).它可以让你从面条一样杂乱的代码中解脱出来:它可以帮你构建一个完美的网络APP,而且每行代码都可以 ...

  5. 高效 Java Web 开发框架 JessMA v3.4.1

    JessMA 是功能完备的高性能 Full-Stack Web 应用开发框架,内置可扩展的 MVC Web 基础架构和 DAO 数据库访问组件(内部已提供了 Hibernate.MyBatis 与 J ...

  6. JavaScript 字符串操作

    JavaScript 字符串用于存储和处理文本.因此在编写 JS 代码之时她总如影随形,在你处理用户的输入数据的时候,在读取或设置 DOM 对象的属性时,在操作 Cookie 时,在转换各种不同 Da ...

  7. jQuery的案例及必知重要的jQuery选择器

    Jquery能做什么 访问和操作DOM元素 控制页面样式 对页面事件进行处理 扩展新的jQuery插件 与Ajax技术完美结合 Jquery的优势 体积小,压缩后只有100KB左右 l强大的选择器 出 ...

  8. 《Web开发中块级元素与行内元素的区分》

    一.块级元素的特性: 占据一整行,总是重起一行并且后面的元素也必须另起一行显示. HTML中块级元素列举如下: address(联系方式信息) article(文章内容) aside(伴随内容) au ...

  9. GitHub Pages 绑定二级域名

    Updated: 2016.06.22 网上搜出一大把,很多还是重复转载的文章,关键是步骤很麻烦,比如:要注册 DNSPod,要 Ping IP(感觉不靠谱,IP是可以变的). 后来看了官方帮助,其它 ...

  10. 好玩的Handler

    Android提供了Handler和Looper来满足线程间的通信; Handler和Activity的任务栈不同,它是先进先出原则; Handler:你可以构造Handler对象来与Looper沟通 ...