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;
    }
};
相关推荐
QXWZ_IA8 小时前
1库1图1批是什么?千寻位置公安地图数据体系详解
科技·算法·能源·媒体·交通物流·政务
c238569 小时前
Bug 猎手入门指南
c++·算法·bug
Reart9 小时前
Leetcode 213.打家劫舍2(内含闲谈,打劫真是技术活,好题,716)
后端·算法
Reart10 小时前
Leetcode 198.打家劫舍(716)
后端·算法
Jerry10 小时前
LeetCode 110. 平衡二叉树
算法
玖玥拾10 小时前
C++ 数据结构 八大基础排序算法专题
数据结构·c++·算法·排序算法
Tim_1011 小时前
【C++】017、new/delete与malloc/free的区别
java·数据结构·算法
YYYing.11 小时前
【C++大型项目之高性能服务器框架 (七) 】Socket与ByteArray模块
服务器·c++·后端·框架·高性能·c/c++
从零开始的代码生活_11 小时前
C++ list 原理与实践:双向链表、迭代器与简化实现
开发语言·c++·后端·学习·算法·链表·list