Skip to content

Commit 25ea392

Browse files
authored
Create 284. Peeking Iterator.py
1 parent 5bcbd4d commit 25ea392

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

‎leetcode3/284. Peeking Iterator.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Below is the interface for Iterator, which is already defined for you.
2+
#
3+
# class Iterator:
4+
# def __init__(self, nums):
5+
# """
6+
# Initializes an iterator object to the beginning of a list.
7+
# :type nums: List[int]
8+
# """
9+
#
10+
# def hasNext(self):
11+
# """
12+
# Returns true if the iteration has more elements.
13+
# :rtype: bool
14+
# """
15+
#
16+
# def next(self):
17+
# """
18+
# Returns the next element in the iteration.
19+
# :rtype: int
20+
# """
21+
22+
class PeekingIterator:
23+
def __init__(self, iterator):
24+
self.iterator = iterator
25+
self.curr = self.iterator.next()
26+
27+
28+
def peek(self):
29+
return self.curr
30+
31+
32+
def next(self):
33+
ans = self.curr
34+
35+
if self.iterator.hasNext():
36+
self.curr = self.iterator.next()
37+
else:
38+
self.curr = None
39+
40+
return ans
41+
42+
43+
def hasNext(self):
44+
return self.curr is not None
45+
46+
47+
# Your PeekingIterator object will be instantiated and called as such:
48+
# iter = PeekingIterator(Iterator(nums))
49+
# while iter.hasNext():
50+
# val = iter.peek() # Get the next element but not advance the iterator.
51+
# iter.next() # Should return the same value as [val].

0 commit comments

Comments
 (0)