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