-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy path284_PeekingIterator.py
48 lines (41 loc) · 1.29 KB
/
284_PeekingIterator.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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: [email protected]
# 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
# """
class PeekingIterator(object):
def __init__(self, iterator):
self.iter = iterator
self.temp = self.iter.next() if self.iter.hasNext() else None
def peek(self):
return self.temp
def next(self):
ret = self.temp
self.temp = self.iter.next() if self.iter.hasNext() else None
return ret
def hasNext(self):
return self.temp is not None
# return not self.temp
# 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].