Skip to content

Commit

Permalink
Added merge nodes solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Dec 22, 2024
1 parent ccae776 commit 568b0ce
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
45 changes: 45 additions & 0 deletions src/leetcode/merge_nodes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#[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 fn merge_nodes(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
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)))
}
}
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,4 @@ mod search_insert;
mod smallest_letter;
mod negative_numbers;
mod guess_number;
mod merge_nodes;

0 comments on commit 568b0ce

Please sign in to comment.