29 lines
431 B
Go
29 lines
431 B
Go
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
|
|
}
|