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;
    }
};
相关推荐
奋斗羊羊5 小时前
【C++】使用MSBuild命令行编译ACE、TAO、DDS
开发语言·c++·windows
zy_destiny5 小时前
【工业场景】用YOLOv8实现行人识别
人工智能·深度学习·opencv·算法·yolo·机器学习
GawynKing6 小时前
红黑树-带源码
数据结构·算法·二叉树··红黑树
Dave.B6 小时前
【VTK实战】vtkDepthImageToPointCloud:从2D深度图到3D点云,手把手教你落地3D扫描/AR场景
算法·计算机视觉·3d·ar·vtk
乐迪信息6 小时前
乐迪信息:煤矿堆煤隐患难排查?AI摄像机实时监控与预警
大数据·人工智能·算法·安全·视觉检测
一语雨在生无可恋敲代码~6 小时前
leetcode724 寻找数组的中心下标
数据结构·算法
史迪奇_xxx6 小时前
9、C/C++ 内存管理详解:从基础到面试题
java·c语言·c++
科研小白_6 小时前
2025年优化算法:多策略改进蛇优化算法( Improved Snake Optimizer,ISO)
算法
88号技师6 小时前
【2025年10月一区SCI】改进策略:Trend-Aware Mechanism 趋势感知机制(TAM)-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
晨非辰6 小时前
《超越单链表的局限:双链表“哨兵位”设计模式,如何让边界处理代码既优雅又健壮?》
c语言·开发语言·数据结构·c++·算法·面试