Skip to main content

2807. Insert Greatest Common Divisors in Linked List

Link

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]:

current = head

while current.next:
nxt = current.next
insert = TreeNode(gcd(current.val, nxt.val))

current.next, insert.next = insert, nxt

current = nxt

return head