-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtwo_stack_array.rb
43 lines (34 loc) · 911 Bytes
/
two_stack_array.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
# Problem:
# Use an array to implement two stacks
class TwoStackArray
class StackFullError < StandardError; end
class StackEmptyError < StandardError; end
attr_accessor :store, :stack_1, :stack_2
def initialize(size)
@store = Array.new(size)
@stack_1 = 0
@stack_2 = size - 1
end
def push(stack_num, item)
raise ArgumentError if stack_num < 1 || stack_num > 2
raise StackFullError if stack_1 > stack_2
index = stack_num == 1 ? stack_1 : stack_2
store[index] = item
if stack_num == 1
@stack_1 += 1
else
@stack_2 -= 1
end
end
def pop(stack_num)
raise ArgumentError if stack_num < 1 || stack_num > 2
if stack_num == 1 && @stack_1 > 0
@stack_1 -= 1
return store[stack_1]
elsif stack_num == 2 && @stack_2 < store.length - 1
@stack_2 += 1
return store[stack_2]
end
raise StackEmptyError
end
end