blob: abb5114871932d12b6be94a674c0ab4a9c046579 (
plain)
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
|
class LinkedListStack
def initialize
@head = Node.new(nil)
end
def push(item)
@head.push(item)
end
def pop
@head.pop
end
def count
visitor = TotalCountVisitor.new
accept(visitor)
visitor.result
end
def accept(visitor)
@head.accept(visitor)
end
end
class Node
attr_reader :data
def initialize(data)
@data = data
end
def push(item)
if @next
@next.push(item)
else
@next = Node.new(item)
end
end
def pop
if @next
if @next.is_tail?
result = @next.data
@next = nil
result
else
@next.pop
end
end
end
def accept(visitor)
visitor.visit(self) if @data
@next.accept(visitor) unless is_tail?
end
def is_tail?
@next == nil
end
end
|