2807. Insert Greatest Common Divisors in Linked List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public ListNode insertGreatestCommonDivisors(ListNode head) {
ListNode curr = head;

while (curr != null) {
ListNode next = curr.next;
if (next != null) {
int gcd = gcd(curr.val, next.val);
ListNode node = new ListNode(gcd);
curr.next = node;
node.next = next;
}

curr = next;
}

return head;
}

private int gcd(int x, int y) {
int remainder = x % y;
if (remainder == 0) {
return y;
} else {
return gcd(y, remainder);
}
}
}

References

2807. Insert Greatest Common Divisors in Linked List