-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148_sort_list.rb
More file actions
52 lines (40 loc) · 837 Bytes
/
148_sort_list.rb
File metadata and controls
52 lines (40 loc) · 837 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
# frozen_string_literal: true
# https://leetcode.com/problems/sort-list/
# @param {ListNode} head
# @return {ListNode}
def sort_list(head)
return head if head.nil? || head.next.nil?
temp = head
slow = head
fast = head
while fast&.next
temp = slow
slow = slow.next
fast = fast.next.next
end
temp.next = nil
left = sort_list(head)
right = sort_list(slow)
merge_nodes(left, right)
end
private
# @param {ListNode} left
# @param {ListNode} right
# @return {ListNode}
def merge_nodes(left, right)
temp = ::ListNode.new(0)
curr = temp
while left && right
if left.val < right.val
curr.next = left
left = left.next
else
curr.next = right
right = right.next
end
curr = curr.next
end
curr.next = left if left
curr.next = right if right
temp.next
end