feat: 2807_insert_greatest_common_divisors_in_linked_list
This commit is contained in:
parent
ed1fa0b0c0
commit
d259727b80
7
2807_insert_greatest_common_divisors_in_linked_list/Cargo.lock
generated
Normal file
7
2807_insert_greatest_common_divisors_in_linked_list/Cargo.lock
generated
Normal file
@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "insert_greatest_common_divisors_in_linked_list"
|
||||
version = "0.1.0"
|
@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "insert_greatest_common_divisors_in_linked_list"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
@ -0,0 +1,63 @@
|
||||
fn main() {
|
||||
println!("{}", Solution::gcd(10, 25));
|
||||
}
|
||||
|
||||
struct Solution;
|
||||
|
||||
#[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 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Solution {
|
||||
pub fn insert_greatest_common_divisors(
|
||||
mut head: Option<Box<ListNode>>,
|
||||
) -> Option<Box<ListNode>> {
|
||||
let mut current = &mut head;
|
||||
|
||||
while let Some(node) = current {
|
||||
if let Some(next_node) = &node.next {
|
||||
let a = node.val;
|
||||
let b = next_node.val;
|
||||
let gcd = Solution::gcd(a, b);
|
||||
|
||||
let next = node.next.take();
|
||||
node.next = Some(Box::new(ListNode { val: gcd, next }));
|
||||
|
||||
current = &mut node.next.as_mut().unwrap().next;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
head
|
||||
}
|
||||
|
||||
fn gcd(mut a: i32, mut b: i32) -> i32 {
|
||||
if a > b {
|
||||
let tmp = a;
|
||||
a = b;
|
||||
b = tmp;
|
||||
}
|
||||
|
||||
loop {
|
||||
let rem = b % a;
|
||||
b = a;
|
||||
a = rem;
|
||||
|
||||
if rem == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
b
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user