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;
    }
};
相关推荐
hanlin032 分钟前
刷题笔记:力扣第84题-柱状图中最大的矩形
笔记·算法·leetcode
青少儿编程课堂1 小时前
威佐夫博弈(双堆取子游戏)解析
c++·python·算法·bfs·信息学竞赛
一个初入编程的小白2 小时前
数据结构:二叉树链式结构的实现
数据结构
辰烨chenye5 小时前
LeetCode Hot 100 题解 · 普通数组篇
算法·leetcode·职场和发展
hqyjzsb8 小时前
零 AI 项目经验,学 Python 转型 AI 的正确顺序是什么?
开发语言·人工智能·python·算法·职场和发展·数据挖掘·数据分析
辰烨chenye8 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
微功夫信息技术8 小时前
分层多智能体强化学习驱动的非急救转运公平 - 效率统一调度系统研究与实践
人工智能·学习·算法·动态规划
sanjiaomao3339 小时前
从论文公式到Python实现:用单元测试校验滑动平均算法
python·算法·单元测试
Keven_119 小时前
算法札记:ACM适用的很骚的C++语法(持续更新)
开发语言·c++
乐迪信息9 小时前
如何通过AI防爆摄像机精准判断船舶超速?
大数据·人工智能·算法·安全·目标跟踪