Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
853 B
2
Indexable
Never
/**
 * 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) {
        ListNode* current = head;
        ListNode* temp;
        ListNode* newNode;
        
        while(current!=NULL && current->next!=NULL) {
            int gcd = __gcd(current->val, current->next->val);
            
            newNode = new ListNode(gcd);
            temp = current;
            
            newNode->next = current->next;
            
            current->next = newNode;
            
            current = newNode->next;
        }
        
        return head;
    }
};
Leave a Comment