# 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
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 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中提供了很多个集合,它们在存储元素时,采用的存储方式不同。我们要取出...