-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstack_as_array.rb
76 lines (62 loc) · 1.24 KB
/
stack_as_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
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
# This file contains the Ruby code from book of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Ruby"
# by Bruno R. Preiss.
#
# Copyright (c) 2004 by Bruno R. Preiss, P.Eng. All rights reserved.
class StackAsArray < Stack
def initialize(size = 0)
super()
@array = Array.new(size)
end
def purge
while @count > 0
@count -= 1
@array[@count] = nil
end
end
def push(obj)
raise ContainerFull if @count == @array.length
@array[@count] = obj
@count += 1
end
def pop
raise ContainerEmpty if @count == 0
@count -= 1
result = @array[@count]
@array[@count] = nil
return result
end
def top
raise ContainerEmpty if @count == 0
return @array[@count - 1]
end
def each
for i in 0 ... @count
yield @array[i]
end
end
attr_reader :array
class Iterator < Opus8::Iterator
def initialize(stack)
@stack = stack
@position = 0
end
def more?
@position < @stack.count
end
def succ
if more?
assert { more? }
result = @stack.array[@position]
@position += 1
else
result = nil
end
return result
end
end
def iter
Iterator.new(self)
end
end