

Python3
方法: 模拟 ⟮O(nlogU)、O(1)⟯
class Solution:
def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head.next is None:
return head
pre = head
cur = head.next
while cur:
temp = ListNode(math.gcd(pre.val, cur.val))
pre.next = temp
temp.next = cur
pre = cur
cur = cur.next
return head

class Solution:
def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
while cur.next:
cur.next = ListNode(math.gcd(cur.val, cur.next.val), cur.next)
cur = cur.next.next
return head
C++
class Solution {
public:
ListNode* insertGreatestCommonDivisors(ListNode* head) {
ListNode* cur = head;
while (cur->next){
cur->next = new ListNode(__gcd(cur->val, cur->next->val), cur->next);
cur = cur->next->next;
}
return head;
}
};