?LeetCode刷題實戰(zhàn)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.
示例
假設(shè)迭代器被初始化為列表 [1,2,3]。
調(diào)用 next() 返回 1,得到列表中的第一個元素。
現(xiàn)在調(diào)用 peek() 返回 2,下一個元素。在此之后調(diào)用 next() 仍然返回 2。
最后一次調(diào)用 next() 返回 3,末尾元素。在此之后調(diào)用 hasNext() 應(yīng)該返回 false。
進(jìn)階:你將如何拓展你的設(shè)計?使之變得通用化,從而適應(yīng)所有的類型,而不只是整數(shù)型?
解題
// 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();
}
}
