mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +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:
parent
cbed4bec90
commit
dcefa07684
1 changed files with 29 additions and 0 deletions
29
go/insert-greatest-common-divisors-in-linked-list.go
Normal file
29
go/insert-greatest-common-divisors-in-linked-list.go
Normal 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
|
||||
}
|
Loading…
Reference in a new issue