-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path284 Peeking Iterator.py
59 lines (49 loc) · 1.38 KB
/
284 Peeking Iterator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that
support the peek() operation -- it essentially peek() at the element that will be returned by the next call to next().
Author: Rajeev Ranjan
"""
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
"""
class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.nxt = None
self.iterator = iterator
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if not self.nxt:
self.nxt = self.iterator.next()
return self.nxt
def next(self):
"""
:rtype: int
"""
ret = self.peek()
self.nxt = None
return ret
def hasNext(self):
"""
:rtype: bool
"""
return self.nxt is not None or self.iterator.hasNext()