284. Peeking Iterator
Design, Array, Iterator ·Problem Statement
link: LeetCode.cn LeetCode
Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations.
Implement the PeekingIterator class:
PeekingIterator(Iterator
Example:
Input: ["PeekingIterator", "next", "peek", "next", "next", "hasNext"][[[1, 2, 3]], [], [], [], [], []]
Output: [null, 1, 2, 2, 3, false]
Solution Approach
The PeekingIterator class initializes with an iterator, and its methods (next, peek, and hasNext) provide functionality to retrieve the next element, peek at the next element without advancing the iterator, and check if there are remaining elements, respectively, utilizing a variable (peeknum) to store the next element.
Algorithm
Implement
class PeekingIterator:
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.it = iterator
self.peeknum = self.it.next() if self.it.hasNext() else None
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self.peeknum
def next(self):
"""
:rtype: int
"""
ret = self.peeknum
self.peeknum = self.it.next() if self.it.hasNext() else None
return ret
def hasNext(self):
"""
:rtype: bool
"""
return self.peeknum is not None