284. Peeking Iterator

# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator(object):
#     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
#         """

#the issue is that when we peek we'll call Iterator().next() as well as when we actually want to get the next elements 
#therefore, in order to avoid calling Iterator().next() twice
#we use a boolean variable to flag if the next element has been looked at (the position of the pointer) 
#and when we have peeked but havent' asked for the element, we'll simply return the peeked element. 
class PeekingIterator(object):
    def __init__(self, iterator):
        """
        Initialize your data structure here.
        :type iterator: Iterator
        """
        #default flag=False, indicate that the next elements hasn't been looked at 
        self.flag=False
        self.iterator=iterator
        

    def peek(self):
        """
        Returns the next element in the iteration without advancing the iterator.
        :rtype: int
        """
        #if the next element hasn't been looked at, store the next value in self.value, then set flag to true 
        if (not self.flag):
            self.value=self.iterator.next()
            self.flag=True
        return self.value
        

    def next(self):
        """
        :rtype: int
        """
        if (not self.flag):
            self.value=self.iterator.next()
        self.flag=False
            
        return self.value
        
        

    def hasNext(self):
        """
        :rtype: bool
        """
        if(self.flag):return True
        if(self.iterator.hasNext()):return True
        return False

# 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].

你可能感兴趣的:(284. Peeking Iterator)