-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathlinked_list.rb
49 lines (42 loc) · 931 Bytes
/
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
# Work with the Linked List structure,
# see examples in test/linked_list_test.rb
module LinkedList
Node = Struct.new(:value, :next)
# Reverses a linked list in the iterative case
def self.reverse(first)
node = first
prev = nil
while node
second = node.next
node.next = prev
prev = node
node = second
end
prev
end
# Deletes duplicates from the list using a hash map, runs in O(n) time
def self.delete_dups(node)
map = {}
prev = nil
while node
if map[node.value]
prev.next = node.next
else
map[node.value] = true
prev = node
end
node = node.next
end
end
# Detects if the linked list has a loop
def self.has_loop?(head)
slow = head
fast = head
while fast && fast.next
slow = slow.next
fast = fast.next.next
return true if slow == fast
end
return false
end
end