-
Notifications
You must be signed in to change notification settings - Fork 3
/
LinkedList.rb
117 lines (95 loc) · 2.08 KB
/
LinkedList.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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# frozen_string_literal: true
# Start with your code from last challenge.
class Node
attr_accessor :next_node, :value
def initialize(value, next_node = nil)
@value = value
@next_node = next_node
end
end
class LinkedList
attr_accessor :count, :head, :tail
def initialize
@count = 0
end
def add(value)
$node = Node.new(value)
if @head.nil?
@head = $node
else
@tail.next_node = $node
end
@count += 1
@tail = $node
end
def add_at(index, value)
# if index is between 0 and count of current nodes - then we can always insert into the node
unless index.between?(0, count)
raise Exception, "Index is out of bounds exception: can insert between 0 and #{count}"
end
# insert at head - special condition
if index == 0 && head.nil?
return add(value)
elsif index == 0 && !head.nil?
self.count += 1
return self.head = Node.new(value, head)
end
$new = Node.new(value)
$prev = head
while index > 1 && $prev
$prev = $prev.next_node
index -= 1
end
self.count += 1
$temp = $prev.next_node
$new.next_node = $temp
$prev.next_node = $new
end
def get(index)
$current = @head
while index > 0 && $current
$current = $current.next_node
index -= 1
end
$current&.value
end
def remove(index)
if index == 0
$temp = @head.next_node
@head = $temp
else
$prev = @head
while index > 1 && $prev
$prev = $prev.next_node
index -= 1
end
$temp = $prev.next_node.next_node
$prev.next_node = $temp
end
end
def print_list
node = head
output = ''
until node.next_node.nil?
output += "#{node.value}, "
node = node.next_node
end
output += node.value.to_s
end
end
list = LinkedList.new
list.add_at(0, 12)
list.add_at(0, 10)
list.add(3)
list.add(5)
list.add_at(1, 11)
# puts list.print_list()
list.add_at(0, 13)
# puts list.print_list()
# puts list.get(0)
# puts list.get(1)
# puts list.get(2)
# => 11
# puts list.get(3)
# => 5
# list.remove(1)