-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove_linked_list_elements.rb
71 lines (54 loc) · 1.13 KB
/
remove_linked_list_elements.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
require 'pry'
=begin
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
=============================================
=end
class ListNode
attr_accessor :val, :next
def initialize(val)
@val = val
@next = nil
end
end
def remove_elements(head, val)
return nil if head.nil?
while head.val == val
return nil if !head.next
head = head.next
end
current = head
while current && current.next do
runner = current.next
while runner && runner.val == val
runner = runner.next || nil
end
current.next = runner
current = current.next
end
head
end
# solution from leetcode:
def remove_elements(head, val)
dummy = ListNode.new(nil)
dummy.next = head
current = dummy
while current && current.next
if current.next.val == val
current.next = current.next.next
else
current = current.next
end
end
dummy.next
end
a = ListNode.new(1)
b = ListNode.new(2)
c = ListNode.new(6)
d = ListNode.new(3)
a.next = b
b.next = c
c.next = d
remove_elements(a, 6)