1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00

go: add «2807. Insert Greatest Common Divisors in Linked List»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-10 11:53:20 +02:00
parent cbed4bec90
commit dcefa07684
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,29 @@
package main
func insertGreatestCommonDivisors(head *ListNode) *ListNode {
gcd := func(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
emplace := func(n *ListNode) *ListNode {
if n.Next == nil {
return n.Next
}
mid := ListNode{
Val: gcd(n.Val, n.Next.Val),
Next: n.Next,
}
n.Next = &mid
return n.Next.Next
}
for node := head; node != nil; {
node = emplace(node)
}
return head
}