-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path284_peeking_iterator.rb
More file actions
47 lines (38 loc) · 851 Bytes
/
284_peeking_iterator.rb
File metadata and controls
47 lines (38 loc) · 851 Bytes
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
# frozen_string_literal: true
# https://leetcode.com/problems/peeking-iterator/
class PeekingIterator
# @param {Iterator} iter
def initialize(iter)
@iterator = iter
@next = @iterator.next
end
# Returns true if the iteration has more elements.
# @return {Integer}
def has_next = !@next.nil?
# Returns the next element in the iteration.
# @return {Integer}
def next
tmp = @next
@next = @iterator.has_next ? @iterator.next : nil
tmp
end
# Returns the next element in the iteration without advancing the iterator.
# @return {Integer}
def peek = @next
end
# Iterator
class Iterator
# @param {Array} v
def initialize(v)
@arr = v
@curr = 0
end
# @return {Boolean}
def has_next = @arr.size > @curr
# @return {Integer}
def next
tmp = @arr[@curr]
@curr += 1
tmp
end
end