2807. Insert Greatest Common Divisors in Linked List
C++
class Solution {
public:
ListNode* insertGreatestCommonDivisors(ListNode* head) {
ListNode* pre = head;
for (ListNode* cur = head->next; cur; cur = cur->next) {
int x = gcd(pre->val, cur->val);
pre->next = new ListNode(x, cur);
pre = cur;
}
return head;
}
};JAVA
class Solution {
public ListNode insertGreatestCommonDivisors(ListNode head) {
for (ListNode pre = head, cur = head.next; cur != null; cur = cur.next) {
int x = gcd(pre.val, cur.val);
pre.next = new ListNode(x, cur);
pre = cur;
}
return head;
}
private int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
}
Comments
Post a Comment