-
Notifications
You must be signed in to change notification settings - Fork 21
/
singly_linked_list.rb
67 lines (54 loc) · 1.05 KB
/
singly_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
require_relative 'node.rb'
class LinkedList
include Enumerable
attr_accessor :length
def initialize
@length = 0
end
def [](pos)
return nil if pos >= @length || pos < 0 # bounds check
index = 0
current_node = @head
while index < pos
current_node = current_node.next
index += 1
end
current_node.data
end
def []=(index, data)
return if index < 0
create_head if @head.nil?
i = 0
current_node = @head
while i < index
create_next_node if i == @length - 1
current_node = current_node.next
i += 1
end
current_node.data = data
end
def each
current_node = @head
(0...@length).each do
yield current_node.data
current_node = current_node.next
end
end
def first
@head.data
end
def last
@tail.data
end
private
def create_head
@head = Node.new
@tail = @head
@length = 1
end
def create_next_node
@tail.next = Node.new
@tail = @tail.next
@length += 1
end
end