-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0622-design-circular-queue.rb
73 lines (58 loc) · 1.23 KB
/
0622-design-circular-queue.rb
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# frozen_string_literal: true
# 622. Design Circular Queue
# https://leetcode.com/problems/design-circular-queue
class MyCircularQueue
# :type k: Integer
def initialize(k)
@queue = [-1] * k
@size = k
@len = 0
@head = 0
end
# :type value: Integer
# :rtype: Boolean
def en_queue(value)
if @len < @size
@queue[(@head + @len) % @size] = value
@len += 1
return true
end
false
end
# :rtype: Boolean
def de_queue
return false if is_empty
@queue[@head] = -1
@head = (@head + 1) % @size
@len -= 1
true
end
# :rtype: Integer
def front
is_empty ? -1 : @queue[@head]
end
# :rtype: Integer
def rear
is_empty ? -1 : @queue[(@head + @len - 1) % @size]
end
# :rtype: Boolean
def is_empty
@len.zero?
end
# :rtype: Boolean
def is_full
@len == @size
end
end
# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue.new(k)
# param_1 = obj.en_queue(value)
# param_2 = obj.de_queue()
# param_3 = obj.front()
# param_4 = obj.rear()
# param_5 = obj.is_empty()
# param_6 = obj.is_full()
# **************** #
# TEST #
# **************** #
# TODO: Write tests