Skip to main content

2807.js

/** ------------------------------------------------------------------------------
*
* 2807. Insert Greatest Common Divisors in Linked List
* Topics: Linked List
* https://leetcode.com/problems/insert-greatest-common-divisors-in-linked-list/description/
*
------------------------------------------------------------------------------ */
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var insertGreatestCommonDivisors = function (head) {
let cur = head

const gcd = (n, m) => {
while (m !== 0) {
const remainder = n % m
n = m
m = remainder
}
return n
}

while (cur.next) {
const value = gcd(cur.val, cur.next.val)
const newNode = {
val: value,
next: cur.next,
}
cur.next = newNode
cur = newNode.next
}

return head
}