-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode_2807.java
45 lines (40 loc) · 1.18 KB
/
Leetcode_2807.java
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
42
43
44
45
class ListNode {
int val; // data
ListNode next; // pointer
ListNode() {} //constructors
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
public ListNode insertGreatestCommonDivisors(ListNode head) {
if( head.next==null) return head;
ListNode node1=head;
ListNode node2=head.next;
while( node2!= null){
int gcdValue=calculateGCD(node1.val, node2.val);
ListNode gcdNode=new ListNode(gcdValue);
node1.next=gcdNode;
gcdNode.next=node2;
node1=node2;
node2=node2.next;
}
return head;
}
private int calculateGCD(int a, int b){
while(b!=0){
int temp=b;
b=a%b;
a=temp;
}
int[] c={a};
return c;
}
}
public class Leetcode_2807{
public static void main(String args[]){
int[] arr={1,2,3,4};
ListNode head=new ListNode(arr);
int b=insertGreatestCommonDivisors(head);
System.out.println(b);
}
}