https://leetcode.com/problems/insert-greatest-common-divisors-in-linked-list
2807. Insert Greateset Common Divisors in Linked List
给一个 linked list 每一个节点都包含一个整数值
在每对相邻节点之间 插入一个新节点 值为两数的最大公约数
返回插入后的 linked list
greatest common divisor 是能整除两个数的最大正整数
Example 1:
Input: head = [18,6,10,3]
Output: [18,6,6,2,10,1,3]
Explanation: gcd(18,6)=6, gcd(6,10)=2, gcd(10,3)=1
https://assets.leetcode.com/uploads/2023/07/18/ex1_copy.png
Example 2:
Input: head = [7]
Output: [7]
Explanation: 没有相邻节点 直接返回原本的 head
https://assets.leetcode.com/uploads/2023/07/18/ex2_copy1.png
Constraints:
节点数 [1, 5000]
节点值 1 <= Node.val <= 1000
思路:
照着做就好
Python Code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from math import gcd
class Solution:
def insertGreatestCommonDivisors(self, head: Optional[ListNode]) ->
Optional[ListNode]:
curr = head
while curr and curr.next:
next_node = curr.next
curr.next = ListNode(gcd(curr.val, next_node.val), next_node)
curr = next_code
return head
怎么又是 Linked List 不过现在对 Linked List 比较懂一些了 还可以