EASY
2807. Insert Greatest Common Divisors in Linked List
You are given the head of a linked list of positive integers. Between every two consecutive nodes, insert a new node whose value is the greatest common divisor (GCD) of the two nodes.
Return the head of the modified linked list.
Example
Input:
head = [18,6,10,3]
[18,6,6,2,10,1,3]
Constraints
- The number of nodes in the list is in the range [1, 1000].
- 1 ≤ Node.val ≤ 1000
Solution: Linked List Traversal
- Time Complexity: O(n), where n is the number of nodes.
- Space Complexity: O(1), in-place modification.
C++
class Solution {
public:
ListNode* insertGreatestCommonDivisors(ListNode* head) {
ListNode* curr = head;
while (curr && curr->next) {
int gcd = __gcd(curr->val, curr->next->val);
ListNode* node = new ListNode(gcd);
node->next = curr->next;
curr->next = node;
curr = node->next;
}
return head;
}
};