-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeeking-iterator.ts
46 lines (41 loc) · 941 Bytes
/
peeking-iterator.ts
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
/**
* // This is the Iterator's API interface.
* // You should not implement it, or speculate about its implementation
* class Iterator {
* hasNext(): boolean {}
*
* next(): number {}
* }
*/
class PeekingIterator {
iterator: Iterator;
head: number | null;
constructor(iterator: Iterator) {
this.iterator = iterator;
if (this.iterator.hasNext()) {
this.head = this.iterator.next()!;
}
}
peek(): number | null {
return this.head;
}
next(): number {
const res = this.head;
if (this.iterator.hasNext()) {
this.head = this.iterator.next();
} else {
this.head = null;
}
return res!;
}
hasNext(): boolean {
return this.head != null;
}
}
/**
* Your PeekingIterator object will be instantiated and called as such:
* var obj = new PeekingIterator(iterator)
* var param_1 = obj.peek()
* var param_2 = obj.next()
* var param_3 = obj.hasNext()
*/