# 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
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Given an Iterator class interface with methods: next() an...
- Question Given an Iterator class interface with methods: ...
- Given an Iterator class interface with methods: next() an...
- "react-native": "0.46.1"这个问题产生原因: /Users/Vanessa/.rncache...
- 06迭代器的概述 A:迭代器概述:a:java中提供了很多个集合,它们在存储元素时,采用的存储方式不同。我们要取出...