Peeking Iterator
To solve this coding challenge, we need to implement a custom iterator class called
that wraps an existing iterator and adds a
method. This method allows us to view the next element without consuming it. We'll also need to implement the existing methods
and
such that they work seamlessly with our new
functionality.
class that satisfies the requirements laid out in the problem description. This class will be capable of peeking at the next element without consuming it, moving to the next element, and checking if more elements are available in the underlying iterator.
PeekingIterator
peek()
next()
hasNext()
peek()
Explanation
Let's break down the problem and the functionalities we need to implement:-
Initialization
: We need to initialize the
PeekingIterator
-
Peek Operation
: The
peek()
-
Next Operation
: The
next()
peek()
-
HasNext Operation
: The
hasNext()
Step-by-Step Explanation/Detailed Steps in Pseudocode
Step 1: Initialization
-
Initialize the
PeekingIterator
-
Set the
peeked_value
None
Step 2: Peek Method
-
Check if there is a
peeked_value
-
If no
peeked_value
peeked_value
Step 3: Next Method
-
Check if there is a
peeked_value
peeked_value
None
-
If no
peeked_value
Step 4: HasNext Method
-
Check if there is a
peeked_value
True
-
If
peeked_value
None
hasNext
Pseudocode with Comments
# PeekingIterator class to extend standard iterator functionalities
class PeekingIterator:
# Constructor method to initialize the class with an existing iterator
method __init__(iterator):
# Store the provided iterator
this.iterator = iterator
# Initialize the peeked_value to None
this.peeked_value = None
# Method to peek the next element without moving the iterator
method peek() -> int:
# If there is no peeked value yet
if this.peeked_value is None:
# Retrieve the next value from the iterator and store in peeked_value
this.peeked_value = this.iterator.next()
# Return the peeked value
return this.peeked_value
# Method to get the next element and move the iterator
method next() -> int:
# If there is a peeked value
if this.peeked_value is not None:
# Store the peeked value in a variable to return it
result = this.peeked_value
# Reset peeked_value to None
this.peeked_value = None
# Return the previous peeked value
return result
# If there is no peeked value, return the next value from the iterator
return this.iterator.next()
# Method to check if there are more elements in the iterator
method hasNext() -> bool:
# Return True if there is a peeked value or if the iterator has more elements
return this.peeked_value is not None or this.iterator.hasNext()
By following this pseudocode, we can implement the
PeekingIterator