Skip to content

Commit acd86bb

Browse files
authored
Create 2807-insert-greatest-common-divisors-in-linked-list.js
1 parent c593f24 commit acd86bb

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @return {ListNode}
11+
*/
12+
const insertGreatestCommonDivisors = function(head) {
13+
const dummy = new ListNode()
14+
15+
dummy.next = head
16+
let cur = head
17+
while(cur.next) {
18+
const val = gcd(cur.val, cur.next.val)
19+
const tmp = new ListNode(val)
20+
const nxt = cur.next
21+
cur.next = tmp
22+
tmp.next = nxt
23+
24+
cur = nxt
25+
}
26+
27+
return dummy.next
28+
29+
function gcd(a, b) {
30+
return b === 0 ? a : gcd(b, a % b)
31+
}
32+
};

0 commit comments

Comments
 (0)