-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path622_design_circular_queue.rb
69 lines (53 loc) · 1.09 KB
/
622_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
# frozen_string_literal: true
require_relative '../common/linked_list'
# https://leetcode.com/problems/design-circular-queue/
class MyCircularQueue
# @param {Integer} k
def initialize(k)
@size = k
@actual_size = 0
@head = ::ListNode.new(0)
@tail = nil
end
# @param {Integer} value
# @return {Boolean}
def en_queue(value)
return false if is_full
if @tail
@tail.next = ::ListNode.new(value)
@tail = @tail.next
else
@tail = ::ListNode.new(value)
@head.next = @tail
end
@tail.next = @head
@actual_size += 1
true
end
# @return {Boolean}
def de_queue
return false if is_empty
if @actual_size == 1
@head.next = nil
@tail = nil
else
@head.next = @head.next.next
end
@actual_size -= 1
true
end
# @return {Integer}
def front
return -1 if is_empty
@head.next.val
end
# @return {Integer}
def rear
return -1 if is_empty
@tail.val
end
# @return {Boolean}
def is_empty = @actual_size.zero?
# @return {Boolean}
def is_full = @size == @actual_size
end