
The task is to design a special iterator, termed PeekingIterator, that extends the functionality of a standard iterator by adding a peek method. This class will be built upon an existing iterator structure and will provide the next element in the sequence without advancing the iterator's position. The PeekingIterator class includes several operations:
PeekingIterator instance.next method.This functionality is particularly useful in scenarios where decision-making depends on the upcoming element without necessarily moving past it.
Input:
Output:
Explanation:
1 <= nums.length <= 10001 <= nums[i] <= 1000next and peek are valid.1000 calls will be made to next, hasNext, and peek.To implement the PeekingIterator, we simulate the normal behavior of an iterator while adding a buffer to store the result of a peek operation.
Constructor Initialization:
PeekingIterator receives a reference to the original iterator and immediately fetches the first value, storing it in a buffer.peek() Method:
next() Method:
hasNext() Method:
This design ensures that the peek operation has no side effects on the traversal sequence, enabling the user to preview the next value safely without altering the iterator’s internal state. The buffer acts as a one-element lookahead, which is updated only when next() is called.
The provided Java solution introduces an AdvancedIterator class that extends the functionality of a standard Iterator<Integer> by allowing an element to be previewed without advancing the iterator. This is particularly useful in scenarios where you want to inspect elements before deciding to move the iterator forward.
Structure Explanation:
AdvancedIterator class maintains a private baseIterator which is the original iterator provided during instantiation.Integer field, upcomingElement, is used to hold the next element from the base iterator. This allows the peek operation to be implemented.Constructor:
peek() can immediately return the next element without altering the state of the iterator.Method peek():
Method next():
next() method but also manages the upcomingElement for subsequent calls.NoSuchElementException if no elements are left, ensuring proper handling of the iterator's bounds.Method hasNext():
upcomingElement.This implementation seamlessly adds the peek functionality to the iterator pattern, enhancing its capabilities while keeping the familiar behavior of standard Java iterators. The class ensures that all usual iterator operations are supported, including robust exception handling for boundary conditions.
0 Comments
Be the first to comment and share your perspective with the community.