Skip to content

Latest commit

 

History

History
78 lines (61 loc) · 1.66 KB

284.md

File metadata and controls

78 lines (61 loc) · 1.66 KB

Peeking Iterator

Description

link


Solution

  • See Code

Code

# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator:
#     def __init__(self, nums):
#         """
#         Initializes an iterator object to the beginning of a list.
#         :type nums: List[int]
#         """
#
#     def hasNext(self):
#         """
#         Returns true if the iteration has more elements.
#         :rtype: bool
#         """
#
#     def next(self):
#         """
#         Returns the next element in the iteration.
#         :rtype: int
#         """

class PeekingIterator:
    def __init__(self, iterator):
        """
        Initialize your data structure here.
        :type iterator: Iterator
        """
        self.iter = iterator
        self.nxt = self.iter.next() if self.iter.hasNext() else None
        

    def peek(self):
        """
        Returns the next element in the iteration without advancing the iterator.
        :rtype: int
        """
        return self.nxt
    

    def next(self):
        """
        :rtype: int
        """
        tmp = self.nxt
        self.nxt = self.iter.next() if self.iter.hasNext() else None
        return tmp
        

    def hasNext(self):
        """
        :rtype: bool
        """
        return self.nxt is not None
        

# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
#     val = iter.peek()   # Get the next element but not advance the iterator.
#     iter.next()         # Should return the same value as [val].