main
1class LinkedListStack
2 def initialize
3 @head = Node.new(nil)
4 end
5
6 def push(item)
7 @head.push(item)
8 end
9
10 def pop
11 @head.pop
12 end
13
14 def count
15 visitor = TotalCountVisitor.new
16 accept(visitor)
17 visitor.result
18 end
19
20 def accept(visitor)
21 @head.accept(visitor)
22 end
23end
24
25class Node
26 attr_reader :data
27
28 def initialize(data)
29 @data = data
30 end
31
32 def push(item)
33 if @next
34 @next.push(item)
35 else
36 @next = Node.new(item)
37 end
38 end
39
40 def pop
41 if @next
42 if @next.is_tail?
43 result = @next.data
44 @next = nil
45 result
46 else
47 @next.pop
48 end
49 end
50 end
51
52 def accept(visitor)
53 visitor.visit(self) if @data
54 @next.accept(visitor) unless is_tail?
55 end
56
57 def is_tail?
58 @next == nil
59 end
60end