21 - Merge Two Sorted Lists

This commit is contained in:
Luke Else 2024-07-19 14:37:48 +01:00
parent ef6c2f5d52
commit 5b09840a8f
2 changed files with 17 additions and 6 deletions

View File

@ -9,7 +9,8 @@ impl Solution for MergeSortedLists {
input: &mut Vec<String>,
) -> Result<Box<dyn std::fmt::Display + Sync>, Box<dyn std::error::Error>> {
let lists = parse_input(input.first().unwrap());
Ok(Box::new(self.merge_two_lists(lists.0, lists.1)))
let merged_list = self.merge_two_lists(lists.0, lists.1);
Ok(Box::new(format!("{:?}", ListNode::to_vec(merged_list)).replace(" ", "")))
}
fn get_id(&self) -> u32 {
@ -42,12 +43,12 @@ impl MergeSortedLists {
}
fn parse_input(input: &str) -> (Option<Box<ListNode>>, Option<Box<ListNode>>) {
let parts: Vec<&str> = input.split(",").collect();
let list1_str = parts[0].split('=').nth(1).unwrap().trim();
let list2_str = parts[1].split('=').nth(1).unwrap().trim();
let parts: Vec<&str> = input.split("],").collect();
let list1_str = parts[0].split('=').nth(1).unwrap().trim().to_string() + "]";
let list2_str = parts[1].split('=').nth(1).unwrap().trim().to_string() + "]";
let list1 = ListNode::from_vec(ListNode::parse_list(list1_str));
let list2 = ListNode::from_vec(ListNode::parse_list(list2_str));
let list1 = ListNode::from_vec(ListNode::parse_list(&list1_str));
let list2 = ListNode::from_vec(ListNode::parse_list(&list2_str));
(list1, list2)
}

View File

@ -24,6 +24,16 @@ impl ListNode {
current
}
pub fn to_vec(node: Option<Box<Self>>) -> Vec<i32> {
let mut vec = Vec::new();
let mut current = node;
while let Some(n) = current {
vec.push(n.val);
current = n.next;
}
vec
}
pub fn parse_list(s: &str) -> Vec<i32> {
s.trim_matches(|c| c == '[' || c == ']')
.split(',')