Peekable Iterator
Implement an iterator of a list of integers nums
where
peek()
returns the next element, without moving the iteratornext()
polls the next element in the iteratorhasnext()
which returns whether the next element exists
Constraints
n ≤ 100,000
wheren
is the number of calls topeek
,next
andhasnext
https://binarysearch.com/problems/Peekable-Iterator
Examples
Example 1
Input
- methods =
['constructor', 'peek', 'next', 'hasnext', 'peek', 'next', 'hasnext']
- arguments =
[[[1, 2]], [], [], [], [], [], []]
Output
- answer =
[None, 1, 1, True, 2, 2, False]
Explanation
- First we create a
PeekableIterator
with values[1, 2]
- We peek the next element which is
1
- We poll the next element which is
1
- We check if the next element exists, which it does since
2
is next in the iterator. - We peek the next element which is
2
- We poll the next element which is
2
- We check if the next element exists which it doesn’t
Leave a comment