You are given the head of a linked list whose nodes hold integers. Between every pair of adjacent nodes, insert a new node whose value is the greatest common divisor of the two. Return the head of the resulting list.
You are given the head of a linked list whose nodes hold integers. Between every pair of adjacent nodes, insert a new node whose value is the greatest common divisor of the two. Return the head of the resulting list.
Example 1:
Input: {"head":[18,6,10,3]}
Output: [18,6,6,2,10,1,3]
Constraints:
The number of nodes in the list is in the range [1,5000].
1≤Node.val≤1000
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"head":[18,6,10,3]}
Walk the 4 original nodes. Between every adjacent pair, insert a new node holding their greatest common divisor, found with Euclid's algorithm.
■ node (a)■ node.next (b)■ inserted gcd node
186103null
Euclid's algorithm: (a, b) → (b, a % b) until b = 0