Skip to content

Commit

Permalink
Add problem 0725: Split Linked List in Parts
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Jun 12, 2024
1 parent 8eda5c4 commit f1934f5
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,7 @@ pub mod problem_0709_to_lower_case;
pub mod problem_0713_subarray_product_less_than_k;
pub mod problem_0717_1_bit_and_2_bit_characters;
pub mod problem_0720_longest_word_in_dictionary;
pub mod problem_0725_split_linked_list_in_parts;
pub mod problem_0738_monotone_increasing_digits;
pub mod problem_0739_daily_temperatures;
pub mod problem_0769_max_chunks_to_make_sorted;
Expand Down
49 changes: 49 additions & 0 deletions src/problem_0725_split_linked_list_in_parts/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use crate::data_structures::ListNode;

pub struct Solution;

impl Solution {
pub fn split_list_to_parts(head: Option<Box<ListNode>>, k: i32) -> Vec<Option<Box<ListNode>>> {
let k = k as usize;
let mut head = head;

let mut result = Vec::with_capacity(k);
let count = std::iter::successors(head.as_ref(), |x| x.next.as_ref()).count();
let size = count / k;

for size in std::iter::repeat(size + 1)
.take(count % k)
.chain(std::iter::repeat(size).take(k - count % k))
{
if size == 0 {
result.push(None);
} else {
let mut pointer = head.as_mut();
for _ in 0..size - 1 {
if let Some(p) = pointer {
pointer = p.next.as_mut();
}
}
let new_head = pointer.unwrap().next.take();
result.push(head);
head = new_head;
}
}

result
}
}

impl super::Solution for Solution {
fn split_list_to_parts(head: Option<Box<ListNode>>, k: i32) -> Vec<Option<Box<ListNode>>> {
Self::split_list_to_parts(head, k)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
36 changes: 36 additions & 0 deletions src/problem_0725_split_linked_list_in_parts/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
pub mod iterative;

use crate::data_structures::ListNode;

pub trait Solution {
fn split_list_to_parts(head: Option<Box<ListNode>>, k: i32) -> Vec<Option<Box<ListNode>>>;
}

#[cfg(test)]
mod tests {
use super::Solution;
use crate::test_utilities;

pub fn run<S: Solution>() {
let test_cases = [
(
(&[1, 2, 3] as &[_], 5),
&[&[1] as &[_], &[2], &[3], &[], &[]] as &[&[_]],
),
(
(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3),
&[&[1, 2, 3, 4], &[5, 6, 7], &[8, 9, 10]],
),
];

for ((head, k), expected) in test_cases {
assert_eq!(
S::split_list_to_parts(test_utilities::make_list(head.iter().copied()), k)
.iter()
.map(|list| test_utilities::iter_list(list).copied().collect::<Vec<_>>())
.collect::<Vec<_>>(),
expected
);
}
}
}

0 comments on commit f1934f5

Please sign in to comment.