# [2807. Insert Greatest Common Divisors in Linked List](https://leetcode.com/problems/insert-greatest-common-divisors-in-linked-list/description) :::spoiler Hint ```cpp= ``` ::: :::spoiler Solution ```cpp= /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* insertGreatestCommonDivisors(ListNode* head) { if (!head->next) return head; ListNode* node1 = head; ListNode* node2 = head->next; while (node2) { int gcdVal = gcd(node1->val, node2->val); ListNode* gcdNode = new ListNode(gcdVal); node1->next = gcdNode; gcdNode->next = node2; node1 = node2; node2 = node2->next; } return head; } }; ``` - T: $O(n \cdot \log(\min(a, b)))$ - S: $O(1)$ :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up