Insert Greatest Common Divisors in Linked List
We need to implement a function that takes the head of a linked list, and for each pair of adjacent nodes, inserts a new node with a value equal to the greatest common divisor (GCD) of the adjacent nodes’ values.
We’ll iterate through the linked list, and for each pair of nodes, we’ll compute the GCD of their values and insert a new node with that value between them.
Here’s the code:
|
|
This code takes advantage of the gcd
function from the math
module to compute the greatest common divisor. It then creates a new node with the computed GCD and inserts it between the current pair of nodes. The process is repeated for all adjacent node pairs in the linked list.
Example:
- For
head = [18,6,10,3]
, the code would return[18,6,6,2,10,1,3]
.