2807. 在链表中插入最大公约数
思路:求最大公约数不难,易错点在于链表的处理。
/**
* 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:
int gcd(int a,int b){
return b?gcd(b,a%b):a;
}
ListNode* insertGreatestCommonDivisors(ListNode* head) {
ListNode * now=new ListNode(0);
ListNode * start=now;
ListNode * p,*q;
p=head,q=head->next;
while(1){
start->next=p;
start=start->next;
if(q==nullptr) break;
int t=gcd(p->val,q->val);
ListNode * tmp=new ListNode(t);
start->next=tmp;
start=start->next;
p=q;
q=p->next;
}
return now->next;
}
};