[LeetCode] Insert Greatest Common Divisors in Linked List

2807. Insert Greatest Common Divisors in Linked List

Given the head of a linked list head, in which each node contains an integer value.

Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them.

Return the linked list after insertion.

The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* insertGreatestCommonDivisors(ListNode* head) {
ListNode* res = head;
ListNode* runner = head->next;
ListNode* tail = res;
while(runner) {
int g = __gcd(tail->val, runner->val);
tail->next = new ListNode(g);
tail = tail->next;
tail->next = runner;
tail = tail->next;
runner = runner->next;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/06/PS/LeetCode/insert-greatest-common-divisors-in-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.