LeetCode刷题实战284:顶端迭代器
PeekingIterator(int[] nums) Initializes the object with the given integer array nums.
int next() Returns the next element in the array and moves the pointer to the next element.
bool hasNext() Returns true if there are still elements in the array.
int peek() Returns the next element in the array without moving the pointer.
示例
假设迭代器被初始化为列表 [1,2,3]。
调用 next() 返回 1,得到列表中的第一个元素。
现在调用 peek() 返回 2,下一个元素。在此之后调用 next() 仍然返回 2。
最后一次调用 next() 返回 3,末尾元素。在此之后调用 hasNext() 应该返回 false。
进阶:你将如何拓展你的设计?使之变得通用化,从而适应所有的类型,而不只是整数型?
解题
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
Iterator<Integer> itr;
boolean peeked;
int peekVal;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
this.itr = iterator;
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
if(peeked) {
return peekVal;
} else {
peeked = true;
peekVal = itr.next();
}
return peekVal;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
if(peeked) {
peeked = false;
return peekVal;
} else return itr.next();
}
@Override
public boolean hasNext() {
return peeked || itr.hasNext();
}
}