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().
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 callpeek()
and it returns 2, the next element. Callingnext()
after that still return 2. You callnext()
the final time and it returns 3, the last element. CallinghasNext()
after that should return false.
Follow up: How would you extend your design to be generic and work with all types, not just integer?
Solution(javascript)
// /**
// * // This is the Iterator's API interface.
// * // You should not implement it, or speculate about its implementation.
// * function Iterator() {
// * @ return {number}
// * this.next = function() { // return the next number of the iterator
// * ...
// * };
// *
// * @return {boolean}
// * this.hasNext = function() { // return true if it still has numbers
// * ...
// * };
// * };
// */
// /** 1: 保存所有的值 O(N) Space
// * @param {Iterator} iterator
// */
// const PeekingIterator = function (iterator) {
// this.list = []
// while (iterator.hasNext()) {
// this.list.push(iterator.next())
// }
// this.index = 0
// }
// /**
// * @return {number}
// */
// PeekingIterator.prototype.peek = function () {
// return this.list[this.index]
// }
// /**
// * @return {number}
// */
// PeekingIterator.prototype.next = function () {
// return this.list[this.index++]
// }
// /**
// * @return {boolean}
// */
// PeekingIterator.prototype.hasNext = function () {
// return this.index < this.list.length
// }
/**
* // This is the Iterator's API interface.
* // You should not implement it, or speculate about its implementation.
* function Iterator() {
* @ return {number}
* this.next = function() { // return the next number of the iterator
* ...
* };
*
* @return {boolean}
* this.hasNext = function() { // return true if it still has numbers
* ...
* };
* };
*/
/** 2: Saving next value O(1) Space
* @param {Iterator} iterator
*/
const PeekingIterator = function (iterator) {
this.nextValue = null
this.iterator = iterator
if (iterator.hasNext()) {
this.nextValue = iterator.next()
}
}
/**
* @return {number}
*/
PeekingIterator.prototype.peek = function () {
return this.nextValue
}
/**
* @return {number}
*/
PeekingIterator.prototype.next = function () {
const value = this.nextValue
if( this.iterator.hasNext()) {
this.nextValue = this.iterator.next()
} else {
this.nextValue = null
}
return value
}
/**
* @return {boolean}
*/
PeekingIterator.prototype.hasNext = function () {
return this.nextValue !== null
}