From 568b0ce6476628dd87f75f52b5cddac26f52566a Mon Sep 17 00:00:00 2001 From: jusexton Date: Sun, 22 Dec 2024 03:59:47 -0600 Subject: [PATCH] Added merge nodes solution. --- README.md | 3 ++- src/leetcode/merge_nodes.rs | 45 +++++++++++++++++++++++++++++++++++++ src/leetcode/mod.rs | 1 + 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/leetcode/merge_nodes.rs diff --git a/README.md b/README.md index 6c59c71..38d9ad5 100644 --- a/README.md +++ b/README.md @@ -248,7 +248,8 @@ programming challenges completed in other languages. - [Container With Most Water](https://leetcode.com/problems/container-with-most-water) - [Max Chunks to Make Sorted](https://leetcode.com/problems/max-chunks-to-make-sorted) - [Valid Sudoku](https://leetcode.com/problems/valid-sudoku) - +- [Merge Nodes In Between Zeroes](https://leetcode.com/problems/merge-nodes-in-between-zeros/) + #### Hard - [Kth Smallest Pair Distance](https://leetcode.com/problems/find-k-th-smallest-pair-distance) diff --git a/src/leetcode/merge_nodes.rs b/src/leetcode/merge_nodes.rs new file mode 100644 index 0000000..0cf45d7 --- /dev/null +++ b/src/leetcode/merge_nodes.rs @@ -0,0 +1,45 @@ +#[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 } + } +} + +pub fn merge_nodes(mut head: Option>) -> Option> { + let mut curr = head.as_deref_mut(); + while let Some(curr_node) = curr.take() { + let mut next_node = curr_node.next.take()?; + let tail = next_node.next.take(); + curr_node.next = tail; + + if next_node.val == 0 { + curr = curr_node.next.as_deref_mut(); + } else { + curr_node.val += next_node.val; + curr = Some(curr_node); + } + } + head +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn merges_values_between_zeroes() { + let tail = Box::new(ListNode::new(0)); + let mut number = Box::new(ListNode::new(5)); + number.next = Some(tail); + let mut head = Box::new(ListNode::new(0)); + head.next = Some(number); + + assert_eq!(Some(Box::new(ListNode::new(5))), merge_nodes(Some(head))) + } +} diff --git a/src/leetcode/mod.rs b/src/leetcode/mod.rs index 0439f28..dafaedc 100644 --- a/src/leetcode/mod.rs +++ b/src/leetcode/mod.rs @@ -156,3 +156,4 @@ mod search_insert; mod smallest_letter; mod negative_numbers; mod guess_number; +mod merge_nodes;