forked from AdaGold/stacks-queues
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathqueue.rb
More file actions
60 lines (53 loc) · 961 Bytes
/
queue.rb
File metadata and controls
60 lines (53 loc) · 961 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
48
49
50
51
52
53
54
55
56
57
58
59
60
QUEUE_SIZE = 20
class Queue
def initialize
@store = Array.new(QUEUE_SIZE)
@front = @rear = -1
end
def enqueue(element)
if @front == -1
@rear = 1
@front = 0
@store[@front] = element
elsif @front == @rear
raise Error, "Queue full"
else
new_rear = (@rear + 1) % QUEUE_SIZE
@store[@rear] = element
@rear = new_rear
end
end
def dequeue
removed = @store[@front]
if @front + 1 == @rear
@front = -1
@rear = -1
else
@store[@front] = nil
@front = (@front + 1) % QUEUE_SIZE
end
return removed
end
def front
if @store.empty?
return -1
else
return @store[@front]
end
end
def size
return @store.size
end
def empty?
return @front == -1
end
def to_s
store_string = []
@store.each do |num|
if num != nil
store_string << num
end
end
return store_string.to_s
end
end