Skip to content

Commit 569fd8a

Browse files
authored
Merge pull request neetcode-gh#2637 from rmrt1n/023
Create 0023-merge-k-sorted-lists.rs
2 parents d6fdecf + 2fa357e commit 569fd8a

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

rust/0023-merge-k-sorted-lists.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
impl Solution {
2+
pub fn merge_k_lists(lists: Vec<Option<Box<ListNode>>>) -> Option<Box<ListNode>> {
3+
fn merge(list1: Option<Box<ListNode>>, list2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
4+
match (list1, list2) {
5+
(None, None) => None,
6+
(None, Some(l)) | (Some(l), None) => Some(l),
7+
(Some(l1), Some(l2)) => {
8+
if l1.val < l2.val {
9+
return Some(Box::new(ListNode {
10+
val: l1.val,
11+
next: merge(l1.next, Some(l2)),
12+
}));
13+
}
14+
Some(Box::new(ListNode {
15+
val: l2.val,
16+
next: merge(Some(l1), l2.next),
17+
}))
18+
}
19+
}
20+
}
21+
22+
if lists.is_empty() {
23+
return None;
24+
}
25+
26+
let mut lists = lists;
27+
28+
while lists.len() > 1 {
29+
let mut merged = vec![];
30+
for i in (0..lists.len()).step_by(2) {
31+
let l1 = lists[i].take();
32+
let l2 = if i + 1 < lists.len() {
33+
lists[i + 1].take()
34+
} else {
35+
None
36+
};
37+
merged.push(merge(l1, l2))
38+
}
39+
lists = merged;
40+
}
41+
42+
lists[0].take()
43+
}
44+
}

0 commit comments

Comments
 (0)