Skip to content

Commit

Permalink
Add problem 2181: Merge Nodes in Between Zeros
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jun 23, 2024
1 parent ef563c5 commit d4f0a1d
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
49 changes: 49 additions & 0 deletions src/problem_2181_merge_nodes_in_between_zeros/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use crate::data_structures::ListNode;

pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn merge_nodes(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
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<Box<ListNode>>) -> Option<Box<ListNode>> {
Self::merge_nodes(head)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
29 changes: 29 additions & 0 deletions src/problem_2181_merge_nodes_in_between_zeros/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use crate::data_structures::ListNode;

pub mod iterative;

pub trait Solution {
fn merge_nodes(head: Option<Box<ListNode>>) -> Option<Box<ListNode>>;
}

#[cfg(test)]
mod tests {
use super::Solution;
use crate::test_utilities;

pub fn run<S: Solution>() {
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::<Vec<_>>(),
expected,
);
}
}
}

0 comments on commit d4f0a1d

Please sign in to comment.