-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_lists.rb
More file actions
98 lines (87 loc) · 2.18 KB
/
linked_lists.rb
File metadata and controls
98 lines (87 loc) · 2.18 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
require 'ruby-debug'
class Node
attr_accessor :next, :value
def initialize(value, linked_list = nil)
@value = value
@next = linked_list
end
def add_to_tail(value, start_node = self)
if start_node.next == nil
node = Node.new(value)
start_node.next = node
return
else
add_to_tail(value, start_node.next)
end
end
def delete(value)
iterate_node = self
return iterate_node.next if iterate_node.value == value
while (iterate_node.next != nil) do
next_node = iterate_node.next
if next_node.value == value
iterate_node.next = next_node.next
return self
end
iterate_node = next_node
end
end
def delete_duplicates
hash_counter = {}
hash_counter[self.value] = true
iterate_node = self
while (iterate_node.next != nil) do
next_node = iterate_node.next
if hash_counter[next_node.value]
iterate_node.next = next_node.next
else
hash_counter[next_node.value] = true
end
iterate_node = next_node
end
end
def nth_to_last_values(nth)
counter = 0
head = self
values = []
while (head != nil) do
values << head.value if counter >= nth
counter += 1
head = head.next
end
values
end
def sum_linked_lists(list)
head = self
list_head = list
values = []
carrier = 0
while (head != nil || list_head != nil) do
head_val = head.nil? ? 0 : head.value
list_head_val = list_head.nil? ? 0 : list_head.value
acum = (head_val + list_head_val + carrier) % 10
carrier = (head_val + list_head_val + carrier) / 10
values << acum
head = head.next if head
list_head = list_head.next if list_head
end
real_numbers = values.reverse
new_list = Node.new(real_numbers[0])
real_numbers.slice(1..-1).each do |val|
new_list.add_to_tail(val)
end
new_list
end
def values
values = []
values << self.value
iterate_node = self
while (iterate_node.next != nil) do
iterate_node = iterate_node.next
values << iterate_node.value
end
values
end
end
linked_list = Node.new(1)
linked_list = linked_list.delete(1)