LeetCode/go/insert-greatest-common-divisors-in-linked-list.go

30 lines
431 B
Go
Raw Normal View History

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
}