Skip to content

Commit dc5301c

Browse files
authored
Merge pull request #940 from Anshika14528/2807
Added Leetcode Problem 2807: #922
2 parents 0b1c81d + 30f6a18 commit dc5301c

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
---
2+
id: insert-greatest-common-divisors-in-linked-list
3+
title: Insert Greatest Common Divisors in Linked List
4+
sidebar_label: 2807 Insert Greatest Common Divisors in Linked List
5+
tags:
6+
- Linked List
7+
- LeetCode
8+
- C++
9+
description: "This is a solution to the Insert Greatest Common Divisors in Linked List problem on LeetCode."
10+
---
11+
12+
## Problem Description
13+
14+
Given the head of a linked list head, in which each node contains an integer value.
15+
16+
Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them.
17+
18+
Return the linked list after insertion.
19+
20+
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
21+
22+
### Examples
23+
24+
**Example 1:**
25+
26+
```
27+
28+
Input: head = [18,6,10,3]
29+
Output: [18,6,6,2,10,1,3]
30+
```
31+
32+
**Example 2:**
33+
34+
```
35+
Input: root = [7]
36+
Output: [7]
37+
```
38+
39+
### Constraints
40+
41+
- The number of nodes in the list is in the range $[1, 5000]$.
42+
- $-1 \leq \text{Node.val} \leq 1000$.
43+
44+
### Approach
45+
46+
To solve this problem(insert greatest common divisors in linked list) we will first store the nodes value of the linked list in vector and then find gcd of each adjacent pair and store it in another vector and then simply iterate the linked list and insert the gcd in the linked list as per the question.
47+
48+
#### Code in C++
49+
50+
```cpp
51+
/**
52+
* Definition for singly-linked list.
53+
* struct ListNode {
54+
* int val;
55+
* ListNode *next;
56+
* ListNode() : val(0), next(nullptr) {}
57+
* ListNode(int x) : val(x), next(nullptr) {}
58+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
59+
* };
60+
*/
61+
class Solution {
62+
public:
63+
ListNode* insertGreatestCommonDivisors(ListNode* head) {
64+
vector<int>a,b;
65+
ListNode* k=head;
66+
while(head!=NULL){
67+
a.push_back(head->val); // store each node value of the given linked list
68+
head=head->next;
69+
}
70+
for(int i=0;i<a.size()-1;i++){ //to store gratest common divisors(gcd) of adjacent pairs
71+
int p=__gcd(a[i],a[i+1]);
72+
b.push_back(p);
73+
}
74+
head=k;
75+
int i=0;
76+
while(k!=NULL && k->next!=NULL){ // inserting gcd between the linked list
77+
ListNode* temp=new ListNode(b[i]);
78+
ListNode* next=k->next;
79+
i++;
80+
k->next=temp;
81+
temp->next=next;
82+
k=k->next->next;
83+
}
84+
return head;
85+
}
86+
};
87+
```
88+
89+

0 commit comments

Comments
 (0)