Given an Iterator class interface with methods:
next()
andhasNext()
, design and implement a PeekingIterator that support thepeek()
operation -- it essentially peek() at the element that will be returned by the next call to next()Here is an example. Assume that the iterator is initialized to the beginning of the list:
[1, 2, 3]
.Call
next()
gets you 1, the first element in the list.Now you call
peek()
and it returns 2, the next element. Callingnext()
after that still return 2.You call
next()
the final time and it returns 3, the last element. CallinghasNext()
after that should return false.Hint:
- Think of "looking ahead". You want to cache the next element.
- Is one variable sufficient? Why or why not?
- Test your design with call order of
peek()
beforenext()
vsnext()
beforepeek()
.- For a clean implementation, check out Google's guava library source code.
Follow up: How would you extend your design to be generic and work with all types, not just integer?
传送门: leetcode Peeking Iterator
题意:
已经给定了Iterator接口
- next()
- hasNext()
让你在此基础上实现PeekingIterator
- peek():返回下一个元素,但指针不移动到下一个
- next(): 移动到下一个元素x并返回x
- hasNext() :返回有下一个元素
思路:
分语言而定,详见代码。
C++
定义peek()方法,而peek可以新建一个临时对象,返回其下一个即可。
至于next 和 hasNext直接用父类的方法即可。
1 | // Below is the interface for Iterator, which is already defined for you. |
Java
建一个成员变量cur,记录下一个指针指向的值。
- peek: 直接返回cur
- next: res = cur , 并 判断是否有下一个,若有则赋值为iterator.next,否则null
- hasNext: 判断cur是否为null
1 | // Java Iterator interface reference: |
Python
同Java 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# 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):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
self.cur = self.iterator.next() if self.iterator.hasNext() else None
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self.cur
def next(self):
"""
:rtype: int
"""
val = self.cur
self.cur = self.iterator.next() if self.iterator.hasNext() else None
return val
def hasNext(self):
"""
:rtype: bool
"""
return self.cur is not None
# 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].