/
1_stack_classes_inspect.rb
70 lines (50 loc) · 1.33 KB
/
1_stack_classes_inspect.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
# A stack is a collection of objects, where when you add a new object to the collection,
# called "pushing", it becomes the first object that you remove from the collection,
# called "popping". Arrays can be used as stacks:
stack = Array.new
stack.push 1
stack.push 2
stack # => [1, 2]
stack.pop # => 2
stack.pop # => 1
stack.pop # => nil
# But I want to implement it using linked lists instead of arrays.
class Node
attr_accessor :next_node, :data
def initialize(next_node, data)
@next_node = next_node
@data = data
end
end
class Stack
def initialize
@head = nil
end
def push(data)
@head = Node.new @head, data
end
def pop
to_return = @head && @head.data
@head &&= @head.next_node
to_return
end
end
stack = Stack.new
stack.push 1
stack.push 2
stack # => #<Stack:0x00000100862698 @head=#<Node:0x00000100862648 @next=#<Node:0x00000100862670 @next=nil, @data=1>, @data=2>>
stack.pop # => 2
stack.pop # => 1
stack.pop # => nil
# Looks good, except that inspection is uuuuuugly. It's the default
# inspect method from Kernel, which knows nothing about our lists.
#
# I want you to override it so that I can do this:
stack = Stack.new
stack.push 1
stack.push 2
stack.push 3
stack # => (3)2)1)
class Stack
# **define the inspect method here**
end