https://leetcode.cn/problems/insert-greatest-common-divisors-in-linked-list/
这道题是在原链表相邻结点的中间插入一个新结点,但是这个新结点的值是这两个相邻结点的最大公约数。
如果要求两个数的最大公约数可以用辗转相除法,这样就可得到两个数的最大公约数。
完整代码如下:
int Maxnum(int x, int y )
{
while(y!=0)
{
int tmp = x % y;
x=y;
y=tmp;
}
return x;
}
struct ListNode* insertGreatestCommonDivisors(struct ListNode* head){
if(head == NULL)
{
return head;
}
struct ListNode* node = head;
while(node->next)
{
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
newnode->val = Maxnum(node->val , node->next->val);
newnode->next = node->next;
node->next = newnode;
node = newnode->next;
}
return head;
}