-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path641_design_circular_deque.rb
95 lines (73 loc) · 1.7 KB
/
641_design_circular_deque.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# frozen_string_literal: true
require_relative '../common/linked_list'
# https://leetcode.com/problems/design-circular-deque/description/
class MyCircularDeque
# @param {Integer} k
def initialize(k)
@size = k
@actual_size = 0
@head = ::ListNode.new(0)
@tail = nil
end
# @param {Integer} value
# @return {Boolean}
def insert_front(value)
return false if is_full
new_head = ::ListNode.new(value)
if @tail
new_head.next = @head.next
@head.next = new_head
else
@tail = new_head
@head.next = @tail
@tail.next = @head
end
@actual_size += 1
true
end
# @param {Integer} value
# @return {Boolean}
def insert_last(value)
return false if is_full
new_tail = ::ListNode.new(value)
if @tail
@tail.next = new_tail
else
@head.next = new_tail
end
@tail = new_tail
@actual_size += 1
true
end
# @param {Boolean}
def delete_front
return false if @actual_size.zero?
@head.next = @head.next.next
@tail = nil if @actual_size == 1
@actual_size -= 1
true
end
# @param {Boolean}
def delete_last
return false if @actual_size.zero?
if @actual_size == 1
@head.next = nil
@tail = nil
else
new_tail = @head.next
new_tail = new_tail.next until new_tail.next == @tail
new_tail.next = @head
@tail = new_tail
end
@actual_size -= 1
true
end
# @return {Integer}
def get_front = @actual_size.zero? ? -1 : @head.next.val
# @return {Integer}
def get_rear = @actual_size.zero? ? -1 : @tail.val
# @return {Boolean}
def is_empty = @actual_size.zero?
# @return {Boolean}
def is_full = @actual_size == @size
end