2181. Merge Nodes in Between Zeros Medium

@problem@discussion
#Linked List#Simulation



1/**
2 * [2181] Merge Nodes in Between Zeros
3 *
4 * You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0.
5 * For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's.
6 * Return the head of the modified linked list.
7 *  
8 * Example 1:
9 * <img alt="" src="https://assets.leetcode.com/uploads/2022/02/02/ex1-1.png" style="width: 600px; height: 41px;" />
10 * Input: head = [0,3,1,0,4,5,2,0]
11 * Output: [4,11]
12 * Explanation: 
13 * The above figure represents the given linked list. The modified list contains
14 * - The sum of the nodes marked in green: 3 + 1 = 4.
15 * - The sum of the nodes marked in red: 4 + 5 + 2 = 11.
16 * 
17 * Example 2:
18 * <img alt="" src="https://assets.leetcode.com/uploads/2022/02/02/ex2-1.png" style="width: 600px; height: 41px;" />
19 * Input: head = [0,1,0,3,0,2,2,0]
20 * Output: [1,3,4]
21 * Explanation: 
22 * The above figure represents the given linked list. The modified list contains
23 * - The sum of the nodes marked in green: 1 = 1.
24 * - The sum of the nodes marked in red: 3 = 3.
25 * - The sum of the nodes marked in yellow: 2 + 2 = 4.
26 * 
27 *  
28 * Constraints:
29 * 
30 * 	The number of nodes in the list is in the range [3, 2 * 10^5].
31 * 	0 <= Node.val <= 1000
32 * 	There are no two consecutive nodes with Node.val == 0.
33 * 	The beginning and end of the linked list have Node.val == 0.
34 * 
35 */
36pub struct Solution {}
37use crate::util::linked_list::{ListNode, to_list};
38
39// problem: https://leetcode.com/problems/merge-nodes-in-between-zeros/
40// discuss: https://leetcode.com/problems/merge-nodes-in-between-zeros/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44// Definition for singly-linked list.
45// #[derive(PartialEq, Eq, Clone, Debug)]
46// pub struct ListNode {
47//   pub val: i32,
48//   pub next: Option<Box<ListNode>>
49// }
50// 
51// impl ListNode {
52//   #[inline]
53//   fn new(val: i32) -> Self {
54//     ListNode {
55//       next: None,
56//       val
57//     }
58//   }
59// }
60impl Solution {
61    pub fn merge_nodes(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
62        Some(Box::new(ListNode::new(0)))
63    }
64}
65
66// submission codes end
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[test]
73    fn test_2181() {
74    }
75}
76


Back
© 2025 bowen.ge All Rights Reserved.