Skip to content

Commit 9731eca

Browse files
committed
Add problem 876: Middle of the Linked List
1 parent bb810ed commit 9731eca

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,7 @@ pub mod problem_0870_advantage_shuffle;
718718
pub mod problem_0872_leaf_similar_trees;
719719
pub mod problem_0874_walking_robot_simulation;
720720
pub mod problem_0875_koko_eating_bananas;
721+
pub mod problem_0876_middle_of_the_linked_list;
721722
pub mod problem_1143_longest_common_subsequence;
722723
pub mod problem_1192_critical_connections_in_a_network;
723724
pub mod problem_1342_number_of_steps_to_reduce_a_number_to_zero;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
use crate::data_structures::ListNode;
2+
3+
pub struct Solution;
4+
5+
// ------------------------------------------------------ snip ------------------------------------------------------ //
6+
7+
use std::iter;
8+
9+
impl Solution {
10+
pub fn middle_node(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
11+
let length = iter::successors(head.as_deref(), |node| node.next.as_deref()).count();
12+
let dropped = length / 2;
13+
let mut node = head;
14+
15+
for _ in 0..dropped {
16+
node = node.unwrap().next;
17+
}
18+
19+
node
20+
}
21+
}
22+
23+
// ------------------------------------------------------ snip ------------------------------------------------------ //
24+
25+
impl super::Solution for Solution {
26+
fn middle_node(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
27+
Self::middle_node(head)
28+
}
29+
}
30+
31+
#[cfg(test)]
32+
mod tests {
33+
#[test]
34+
fn test_solution() {
35+
super::super::tests::run::<super::Solution>();
36+
}
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
use crate::data_structures::ListNode;
2+
3+
pub mod iterative;
4+
5+
pub trait Solution {
6+
fn middle_node(head: Option<Box<ListNode>>) -> Option<Box<ListNode>>;
7+
}
8+
9+
#[cfg(test)]
10+
mod tests {
11+
use super::Solution;
12+
use crate::test_utilities;
13+
14+
pub fn run<S: Solution>() {
15+
let test_cases = [
16+
(&[1, 2, 3, 4, 5] as &[_], &[3, 4, 5] as &[_]),
17+
(&[1, 2, 3, 4, 5, 6], &[4, 5, 6]),
18+
];
19+
20+
for (head, expected) in test_cases {
21+
assert_eq!(
22+
test_utilities::iter_list(&S::middle_node(test_utilities::make_list(head.iter().copied())))
23+
.copied()
24+
.collect::<Box<_>>()
25+
.as_ref(),
26+
expected
27+
);
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)