-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.rb
104 lines (88 loc) · 1.54 KB
/
stack.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
96
97
98
99
100
101
102
103
104
# Stack
#
# Usage:
#
# s = Stack.new
# => s.empty?
# true
# => s.push('Test 1')
# <Node 1234: value="Test 1">
# => s.push('Test 2')
# <Node 1235: value="Test 2">
# => s.count
# 2
# => s.each { |node| puts node.value }
# Test 1
# Test 2
# => s.pop
# <Node 1235: value="Test 2">
# => s.top
# <Node 1234: value="Test 1">
class Stack
attr_accessor :top
# Push a value onto the stack
# value: Any Object
#
# Returns a new Node
def push(value)
node = Node.new(value)
node.previous = top
self.top = node
return node
end
# Pop a value off the top of the stack
#
# Returns the Node at the top of the stack
def pop
return nil if empty?
node = top
self.top = node.previous
return node
end
# Is the Stack empty?
#
# Returns a Boolean
def empty?
return top.nil?
end
# Count the number of nodes in the Stack
#
# Returns an Integer
def count
count = 0
each do |node|
count += 1
end
return count
end
# Loop over each Node in the stack
# block: Block
#
# Returns the first node in the Stack
def each(&block)
node = top
while node
if block
block.yield(node)
end
if node.previous
node = node.previous
else
break
end
end
return node
end
class Node
attr_accessor :value
attr_accessor :previous
# Initialize a new Node
# value: Any Object
def initialize(value)
self.value = value
end
def inspect
"<Node #{object_id}: value=#{value.inspect}>"
end
end
end