-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeekingIterator.java
More file actions
51 lines (42 loc) · 1.25 KB
/
PeekingIterator.java
File metadata and controls
51 lines (42 loc) · 1.25 KB
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
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Author : WindAsMe
* File : PeekingIterator.java
* Time : Create on 18-8-8
* Location : ../Home/JavaForLeeCode2/PeekingIterator.java
* Function : LeetCode No.284
*/
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
private List<Integer> list;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
list = new ArrayList<>();
while (iterator.hasNext())
list.add(iterator.next());
}
// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
if (list.size() != 0)
return list.get(0);
return null;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
if (list.size() != 0) {
Integer ans = list.get(0);
list.remove(0);
return ans;
}
return null;
}
@Override
public boolean hasNext() {
return list.size() != 0;
}
}