-
Notifications
You must be signed in to change notification settings - Fork 252
/
simple_linked_list.rb
71 lines (64 loc) · 1.3 KB
/
simple_linked_list.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
# Problem : https://exercism.org/tracks/ruby/exercises/simple-linked-list
# Solution
class Element
attr_accessor :next,:datum
def initialize(data)
@datum = data
@next = nil
end
end
class SimpleLinkedList
def initialize(elements=[])
@head = nil
elements.each do |element|
push(Element.new(element))
end
end
def push(element)
if @head.nil?
@head = element
else
tail = find_tail
tail.next = element
end
self
end
def pop
current = @head
if @head.nil? or @head.next.nil?
@head = nil
return current
end
current = current.next until current.next.next.nil?
last_node = current.next
current.next = nil
last_node
end
def to_a
current = @head
data = []
until current.nil?
data.push(current.datum)
current = current.next
end
data.reverse
end
def reverse!
current = @head
prev = nil
until current.nil?
next_node = current.next
current.next = prev
prev = current
current = next_node
end
@head = prev
self
end
private
def find_tail
node = @head
node = node.next until node.next.nil?
node
end
end