Skip to content

Commit a9d7942

Browse files
committed
src/bin/merge-nodes-in-between-zeros.rs
1 parent 3db192e commit a9d7942

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#![allow(dead_code, unused, unused_variables, non_snake_case)]
2+
3+
fn main() {}
4+
5+
struct Solution;
6+
7+
// Definition for singly-linked list.
8+
#[derive(PartialEq, Eq, Clone, Debug)]
9+
pub struct ListNode {
10+
pub val: i32,
11+
pub next: Option<Box<ListNode>>,
12+
}
13+
14+
impl ListNode {
15+
#[inline]
16+
fn new(val: i32) -> Self {
17+
ListNode { next: None, val }
18+
}
19+
}
20+
21+
impl Solution {
22+
pub fn merge_nodes(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
23+
let mut result = ListNode::new(0);
24+
let mut next = &mut result.next;
25+
let mut current = head.unwrap().next;
26+
27+
let mut val = 0;
28+
while current.is_some() {
29+
if current.as_ref().unwrap().val == 0 {
30+
next.insert(Box::new(ListNode::new(val)));
31+
val = 0;
32+
next = &mut next.as_mut().unwrap().next;
33+
} else {
34+
val += current.as_ref().unwrap().val;
35+
}
36+
37+
current = current.unwrap().next;
38+
}
39+
40+
result.next.take()
41+
}
42+
}

0 commit comments

Comments
 (0)