-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.rb
139 lines (126 loc) · 2.56 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
require "./Node"
require 'pry'
class LinkedList
attr_accessor :head, :next_node
def initialize
@head = nil
end
def append(data)
if invalid_word?(data)
nil
elsif @head.nil?
@head = Node.new(data)
else
find_tail.next_node = Node.new(data)
end
data
end
def insert(position, data)
if invalid_word?(data)
nil
else
@head = Node.new(data) if empty?
if position == 0
prepend(data)
else position > 0
current = @head
count = 0
until position - 1 == count
count += 1
current = current.next_node
end
reattach_node = current.next_node
current.next_node = Node.new(data)
current.next_node.next_node = reattach_node
end
end
end
def prepend(data)
if invalid_word?(data)
nil
else
head = Node.new(data)
head.next_node = @head
@head = head
data
end
end
def empty?
if head.nil?
true
end
end
def count
if empty?
counter = 0
else
current = @head
counter = 1
until current.next_node.nil?
counter += 1
current = current.next_node
end
end
counter
end
def to_string
string = "#{@head.data} "
current = @head
until current.next_node == nil
current = current.next_node
string << current.data + " "
end
string.strip
end
def find_tail
current = @head
until current.next_node.nil?
current = current.next_node
end
current
end
def includes?(chunk)
false if empty?
current = @head
until current.data == chunk
current = current.next_node
break if find_tail.data != chunk
end
current.data == chunk
end
def find(position, length)
current = @head
count = 1
until position == count
count += 1
current = current.next_node
end
string = ""
length.times do
string << current.data + " "
current = current.next_node
end
string.strip
end
def pop
tail_return = find_tail.data
current = @head
counter = 1
if current.next_node == nil
current.data = nil
else
until counter + 1 == count
counter += 1
current = current.next_node
end
if counter + 1 == count
current.next_node = nil
end
end
tail_return
end
def invalid_word?(data)
invalid_words = ["Charlie", "Mississippi", "Patagonia", "Junngle", "Beats", "Turing"]
invalid_words.include?(data.to_s)
end
end