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.
Example 1
[18] -> [6] -> [10] -> [3] -> null --- [18] -> [6] -> [6] -> [2] -> [10] -> [1] -> [3] -> null
Input
head = [18,6,10,3]Output
[18,6,6,2,10,1,3]We insert gcd values 6, 2, and 1 between each adjacent pair, then return the resulting linked list.
Example 2
[7] -> null --- [7] -> null
Input
head = [7]Output
[7]There are no pairs of adjacent nodes, so we return the initial linked list.
Constraints
- The number of nodes in the list is in the range
[1, 5000]. 1 <= Node.val <= 1000