Skip to content

Commit 91eb35f

Browse files
committed
Revise ruby solution 021 and add 023
1 parent 817d04c commit 91eb35f

File tree

2 files changed

+49
-24
lines changed

2 files changed

+49
-24
lines changed

solution/021.Merge Two Sorted Lists/Solution.rb

+10-24
Original file line numberDiff line numberDiff line change
@@ -11,29 +11,15 @@
1111
# @param {ListNode} l2
1212
# @return {ListNode}
1313
def merge_two_lists(l1, l2)
14-
return l1 if l2.nil?
15-
return l2 if l1.nil?
16-
17-
head = ListNode.new(0)
18-
temp = head
19-
20-
until l1.nil? && l2.nil?
21-
if l1.nil?
22-
head.next = l2
23-
break
24-
elsif l2.nil?
25-
head.next = l1
26-
break
27-
elsif l1.val < l2.val
28-
head.next = ListNode.new(l1.val)
29-
head = head.next
30-
l1 = l1.next
31-
else
32-
head.next = ListNode.new(l2.val)
33-
head = head.next
34-
l2 = l2.next
35-
end
14+
if l1.nil?
15+
l2
16+
elsif l2.nil?
17+
l1
18+
elsif l1.val < l2.val
19+
l1.next = merge_two_lists(l1.next, l2)
20+
l1
21+
else
22+
l2.next = merge_two_lists(l1, l2.next)
23+
l2
3624
end
37-
temp.next
3825
end
39-
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Definition for singly-linked list.
2+
# class ListNode
3+
# attr_accessor :val, :next
4+
# def initialize(val)
5+
# @val = val
6+
# @next = nil
7+
# end
8+
# end
9+
10+
# @param {ListNode[]} lists
11+
# @return {ListNode}
12+
def merge_k_lists(lists)
13+
if lists.nil?
14+
nil
15+
elsif lists.length == 1
16+
lists[0]
17+
else
18+
cur_list = lists[0]
19+
for i in 1..lists.length - 1
20+
cur_list = merge_2_lists(cur_list, lists[i])
21+
end
22+
cur_list
23+
end
24+
25+
end
26+
27+
def merge_2_lists(list_a, list_b)
28+
if list_a.nil?
29+
list_b
30+
elsif list_b.nil?
31+
list_a
32+
elsif list_a.val < list_b.val
33+
list_a.next = merge_2_lists(list_a.next, list_b)
34+
list_a
35+
else
36+
list_b.next = merge_2_lists(list_a, list_b.next)
37+
list_b
38+
end
39+
end

0 commit comments

Comments
 (0)