LeetCode2807. Insert Greatest Common Divisors in Linked List

文章目录

一、题目

Given the head of a linked list head, in which each node contains an integer value.

Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them.

Return the linked list after insertion.

The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

Example 1:

Input: head = [18,6,10,3]

Output: [18,6,6,2,10,1,3]

Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes).

  • We insert the greatest common divisor of 18 and 6 = 6 between the 1st and the 2nd nodes.
  • We insert the greatest common divisor of 6 and 10 = 2 between the 2nd and the 3rd nodes.
  • We insert the greatest common divisor of 10 and 3 = 1 between the 3rd and the 4th nodes.
    There are no more adjacent nodes, so we return the linked list.
    Example 2:

Input: head = [7]

Output: [7]

Explanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes.

There are no pairs of adjacent nodes, so we return the initial linked list.

Constraints:

The number of nodes in the list is in the range [1, 5000].

1 <= Node.val <= 1000

二、题解

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* insertGreatestCommonDivisors(ListNode* head) {
        ListNode* cur = head;
        while(cur && cur->next){
            int k = gcd(cur->val,cur->next->val);
            ListNode* t = new ListNode(k,cur->next);
            cur->next = t;
            cur = cur->next->next;
        }
        return head;
    }
};
相关推荐
木井巳14 分钟前
【递归算法】二叉搜索树中第K小的元素
java·算法·leetcode·深度优先·剪枝
铉铉这波能秀15 分钟前
LeetCode Hot100 中 enumerate 函数的妙用(2026.2月版)
数据结构·python·算法·leetcode·职场和发展·开发
墨有66623 分钟前
哈希表从入门到实现,一篇吃透!
数据结构·算法·哈希算法
Yu_Lijing24 分钟前
网络复习篇——网络基础(一)
网络·c++·笔记
Bella的成长园地26 分钟前
为什么c++中的条件变量的 wait() 函数需要配合while 循环或谓词?
c++·面试
We་ct27 分钟前
LeetCode 228. 汇总区间:解题思路+代码详解
前端·算法·leetcode·typescript
charlee4427 分钟前
为什么现代 C++ 库都用 PIMPL?一场关于封装、依赖与安全的演进
c++·智能指针·raii·pimpl·编译防火墙·封装设计
AIpanda88832 分钟前
如何借助AI销冠系统提升数字员工在销售中的成效?
算法
啊阿狸不会拉杆32 分钟前
《机器学习导论》第 7 章-聚类
数据结构·人工智能·python·算法·机器学习·数据挖掘·聚类
木非哲38 分钟前
机器学习--从“三个臭皮匠”到 XGBoost:揭秘 Boosting 算法的“填坑”艺术
算法·机器学习·boosting