diff --git a/src/lib.rs b/src/lib.rs index c8159301..3318007a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1549,6 +1549,7 @@ pub mod problem_2169_count_operations_to_obtain_zero; pub mod problem_2170_minimum_operations_to_make_the_array_alternating; pub mod problem_2177_find_three_consecutive_integers_that_sum_to_a_given_number; pub mod problem_2180_count_integers_with_even_digit_sum; +pub mod problem_2181_merge_nodes_in_between_zeros; pub mod problem_2185_counting_words_with_a_given_prefix; pub mod problem_2186_minimum_number_of_steps_to_make_two_strings_anagram_ii; pub mod problem_2190_most_frequent_number_following_key_in_an_array; diff --git a/src/problem_2181_merge_nodes_in_between_zeros/iterative.rs b/src/problem_2181_merge_nodes_in_between_zeros/iterative.rs new file mode 100644 index 00000000..95a5b360 --- /dev/null +++ b/src/problem_2181_merge_nodes_in_between_zeros/iterative.rs @@ -0,0 +1,49 @@ +use crate::data_structures::ListNode; + +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn merge_nodes(head: Option>) -> Option> { + let mut result = None; + let mut tail = &mut result; + let mut iter = head; + + while let Some(mut node) = iter { + let mut sum = node.val; + + loop { + node = node.next.unwrap(); + + if node.val == 0 { + iter = node.next.take(); + node.val = sum; + tail = &mut tail.insert(node).next; + + break; + } + + sum += node.val; + } + } + + result + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn merge_nodes(head: Option>) -> Option> { + Self::merge_nodes(head) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2181_merge_nodes_in_between_zeros/mod.rs b/src/problem_2181_merge_nodes_in_between_zeros/mod.rs new file mode 100644 index 00000000..20549bdf --- /dev/null +++ b/src/problem_2181_merge_nodes_in_between_zeros/mod.rs @@ -0,0 +1,29 @@ +use crate::data_structures::ListNode; + +pub mod iterative; + +pub trait Solution { + fn merge_nodes(head: Option>) -> Option>; +} + +#[cfg(test)] +mod tests { + use super::Solution; + use crate::test_utilities; + + pub fn run() { + let test_cases = [ + (&[0, 3, 1, 0, 4, 5, 2, 0], &[4, 11] as &[_]), + (&[0, 1, 0, 3, 0, 2, 2, 0], &[1, 3, 4]), + ]; + + for (head, expected) in test_cases { + assert_eq!( + &test_utilities::iter_list(&S::merge_nodes(test_utilities::make_list(head.iter().copied()))) + .copied() + .collect::>(), + expected, + ); + } + } +}