-
-
Notifications
You must be signed in to change notification settings - Fork 519
/
Copy pathexample.rb
55 lines (48 loc) · 873 Bytes
/
example.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
class Element
attr_reader :datum
attr_accessor :next
def initialize(value)
@datum = value
@next = nil
end
end
class SimpleLinkedList
def initialize(array = [])
create_from_array(array)
end
def to_a
result = []
pointer = @head
while pointer
result << pointer.datum
pointer = pointer.next
end
result
end
def push(element)
element.next = @head unless @head.nil?
@head = element
self
end
def pop
element = @head
@head = element.next if element
element
end
def reverse!
previous = nil
pointer = @head
while pointer
temp = pointer.next
pointer.next = previous
previous = pointer
pointer = temp
end
@head = previous
self
end
private
def create_from_array(array)
array.each { |value| push(Element.new(value)) }
end
end