feat: 2181_merge_nodes_in_between_zeros

This commit is contained in:
SquidSpirit 2025-08-20 01:24:38 +08:00
parent ea3f8dfd88
commit 349b9de617
3 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "merge_nodes_in_between_zeros"
version = "0.1.0"

View File

@ -0,0 +1,6 @@
[package]
name = "merge_nodes_in_between_zeros"
version = "0.1.0"
edition = "2024"
[dependencies]

View File

@ -0,0 +1,39 @@
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
pub struct Solution;
impl Solution {
pub fn merge_nodes(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut result_head = Some(Box::new(ListNode::new(0)));
let mut result_current_node = &mut result_head;
let mut current_node = head.unwrap().next;
while let Some(node) = current_node.take() {
if node.val != 0 {
result_current_node.as_mut().unwrap().val += node.val;
} else {
if node.next.as_ref().is_none() {
break;
}
result_current_node.as_mut().unwrap().next = Some(Box::new(ListNode::new(0)));
result_current_node = &mut result_current_node.as_mut().unwrap().next;
}
current_node = node.next;
}
result_head
}
}