From c3d977118be4e87ea20c0779540be3142ed34d88 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 24 May 2024 09:25:16 +0800 Subject: [PATCH] 20240524 Finished --- src/problem/mod.rs | 3 +- src/problem/p21_merge_two_sorted_lists.rs | 67 +++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 src/problem/p21_merge_two_sorted_lists.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index dbe297c..d4e1069 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -137,4 +137,5 @@ mod p452_minimum_number_of_arrows_to_burst_balloons; mod p71_simplify_path; mod p155_min_stack; mod p150_evaluate_reverse_polish_notation; -mod p224_basic_calculator; \ No newline at end of file +mod p224_basic_calculator; +mod p21_merge_two_sorted_lists; \ No newline at end of file diff --git a/src/problem/p21_merge_two_sorted_lists.rs b/src/problem/p21_merge_two_sorted_lists.rs new file mode 100644 index 0000000..9709446 --- /dev/null +++ b/src/problem/p21_merge_two_sorted_lists.rs @@ -0,0 +1,67 @@ +/** + * [21] Merge Two Sorted Lists + */ +pub struct Solution {} + +use std::borrow::{Borrow, BorrowMut}; + +use crate::util::linked_list::{ListNode, to_list}; + +// submission codes start here + +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn merge_two_lists(list1: Option>, list2: Option>) -> Option> { + let mut head = None; + let mut now = &mut head; + + let (mut list1, mut list2) = (list1, list2); + + *now = loop { + match (list1, list2) { + (Some(mut a), Some(mut b)) => { + if a.val < b.val { + list1 = a.next.take(); + list2 = Some(b); + + now = &mut now.insert(a).next; + } else { + list1 = Some(a); + list2 = b.next.take(); + + now = &mut now.insert(b).next + } + }, + (x, y) => break x.or(y) + } + }; + + head + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_21() { + } +}