-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.rb
More file actions
62 lines (39 loc) · 714 Bytes
/
Solution.rb
File metadata and controls
62 lines (39 loc) · 714 Bytes
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
# Definition for singly-linked list.
class ListNode
attr_accessor :val, :next
def initialize(val)
@val = val
@next = nil
end
end
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def merge_two_lists(l1, l2)
if l1.nil?
return l2
end
if l2.nil?
return l1
end
head = l1.val < l2.val ? l1 : l2
ptr = head
ptr1 = head == l1 ? l1.next : l1
ptr2 = head == l2 ? l2.next : l2
until ptr1.nil? or ptr2.nil?
if ptr1.val <= ptr2.val
ptr.next = ptr1
ptr1 = ptr1.next
else
ptr.next = ptr2
ptr2 = ptr2.next
end
ptr = ptr.next
end
if ptr1.nil?
ptr.next = ptr2
else
ptr.next = ptr1
end
head
end