-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
41 lines (40 loc) · 1.22 KB
/
Copy pathsolution.java
File metadata and controls
41 lines (40 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 2807. Insert Greatest Common Divisors in Linked List
// https://leetcode.com/problems/insert-greatest-common-divisors-in-linked-list/
// Medium | Java | Accepted 2026-08-29
// Runtime 1 ms | Memory 47 MB
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode insertGreatestCommonDivisors(ListNode head) {
ListNode dummy = new ListNode();
dummy.next = head;
dummy = dummy.next;
while(dummy!=null && dummy.next!=null)
{
int curr = dummy.val;
int next = dummy.next.val;
ListNode nex = dummy.next;
int start = Math.max(curr, next);
int divide = Math.min(curr, next);
while(divide>0)
{
int temp = divide;
divide = start%temp;
start = temp;
}
ListNode insert = new ListNode(start);
dummy.next = insert;
insert.next = nex;
dummy = nex;
}
return head;
}
}