From f4dcf1a23d0ad3b1eb7049f20cc7dd63adac45de Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 9 Sep 2024 11:46:49 +0800 Subject: [PATCH] 20240909 finished. --- src/problem/mod.rs | 3 +- .../p2181_merge_nodes_in_between_zeros.rs | 68 +++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 src/problem/p2181_merge_nodes_in_between_zeros.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 0b7cabf..01387a7 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -229,4 +229,5 @@ mod p2860_happy_students; mod p3174_clear_digits; mod p3176_find_the_maximum_length_of_a_good_subsequence_i; mod p3177_find_the_maximum_length_of_a_good_subsequence_ii; -mod p977_squares_of_a_sorted_array; \ No newline at end of file +mod p977_squares_of_a_sorted_array; +mod p2181_merge_nodes_in_between_zeros; \ No newline at end of file diff --git a/src/problem/p2181_merge_nodes_in_between_zeros.rs b/src/problem/p2181_merge_nodes_in_between_zeros.rs new file mode 100644 index 0000000..0b5f467 --- /dev/null +++ b/src/problem/p2181_merge_nodes_in_between_zeros.rs @@ -0,0 +1,68 @@ +/** + * [2181] Merge Nodes in Between Zeros + */ +pub struct Solution {} + +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_nodes(head: Option>) -> Option> { + let mut array = Vec::new(); + let mut value = 0; + let mut node = head; + + while let Some(n) = node { + if n.val == 0 { + if value != 0 { + array.push(value); + value = 0; + } + } else { + value += n.val; + } + + node = n.next; + } + + let mut current = None; + + for &i in array.iter().rev() { + let mut n = ListNode::new(i); + n.next = current; + current = Some(Box::new(n)); + } + + current + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2181() { + assert_eq!(to_list(vec![4, 11]), Solution::merge_nodes(to_list(vec![0, 3, 1, 0, 4, 5, 2, 0]))); + assert_eq!(to_list(vec![1, 3, 4]), Solution::merge_nodes(to_list(vec![0, 1, 0, 3, 0, 2, 2, 0]))); + } +}