Description:

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.

Hint:

  1. Think of "looking ahead". You want to cache the next element.Show More Hint

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.

就是利用Java中的Iterator接口来实现一个类,主要是peek()方法的实现与API中的不同,可以在peek()和next()中同时使用Iterator.next()来实现。

设置一个top来保存当前值。

 // Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> { private Iterator<Integer> it; private Integer top = null; public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
it = iterator;
} // Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
Integer peek;
if(top != null) {
peek = top;
}
else {
peek = top = next();
}
return peek;
} // hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
Integer next = 0;
if(top != null) {
next = top;
top = null;
}
else {
next = it.next();
}
return next;
} @Override
public boolean hasNext() {
if(top != null) {
return true;
}
return it.hasNext();
}
}

最新文章

  1. jquery弹出可关闭遮罩提示框
  2. jquery 的队列queue
  3. go语言指针符号的*和&amp;
  4. jQuery动态五星评分
  5. PHP创建定义数组
  6. json_encode()中文不转码
  7. OBS源码解析(3)OBSApp类介绍
  8. 微信小程序之使用本地接口开发
  9. vmstat结果在不同操作系统上的解释
  10. let 和 const 命令
  11. JavaScript中将对象数组中的某个属性值,批量替换成另一个数值
  12. Pyspark-SQL 官方 API 的一些梳理(上)
  13. 强大的IDEA开发工具
  14. bash配色
  15. Java 虚拟机面试题全面解析(干货)
  16. Luogu5155 USACO18DEC Balance Beam(概率期望+凸包)
  17. C++:实现类似MFC的IsKindOf功能
  18. Elasticsearch学习之head插件安装
  19. ubuntu16.04 LTS Server 安装mysql phpmyadmin apache2 php5.6环境
  20. Codeforces554C:Kyoya and Colored Balls(组合数学+费马小定理)

热门文章

  1. EFM32 DMA/PRS例程
  2. 轻量级ORM框架Dapper应用五:使用Dapper实现Join操作
  3. 执行一条sql语句update多条不同值的记录实现思路
  4. Cracking the coding interview--Q3.1
  5. 用Jquery获取checkbox多个选项
  6. (三)使用预定义模型QDirModel的例子
  7. [转] C# mysql 事务回滚
  8. 【Android实战】Android中处理崩溃异常
  9. PHP生成UTF-8编码的CSV文件用Excel打开乱码的解决办法
  10. 《开源框架那些事儿22》:UI框架设计实战