目录
一、题目
1、题目描述
2、接口描述
/**
* 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) {
}
};
3、原题链接
2807. 在链表中插入最大公约数
二、解题报告
1、思路分析
直接模拟即可
2、复杂度
3、代码详解
/**
* 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 {
typedef ListNode Node;
public:
int gcd(int x , int y)
{
if(x < y) swap(x , y);
if(!y) return x;
return gcd(y , x % y);
}
ListNode* insertGreatestCommonDivisors(ListNode* head) {
Node* cur = head , *nxt = head -> next;
while(cur)
{
nxt = cur -> next;
if(nxt)
cur -> next = new Node(gcd(cur->val , nxt->val) , nxt);
cur = nxt;
}
return head;
}
};