2807.在链表中插入最大公约数
小于 1 分钟
2807.在链表中插入最大公约数
/*
* @lc app=leetcode.cn id=2807 lang=typescript
*
* [2807] 在链表中插入最大公约数
*/
// @lc code=start
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function insertGreatestCommonDivisors(head: ListNode | null): ListNode | null {
if (head == null) return null;
let current: ListNode | null = head; // 遍历用
let p = head; // 记录前节点
while (current) {
let n = p.next;
if (n != null) {
// 下一节点存在时,计算最大公约数
let valNode = new ListNode(greatestCommonDivisor(p.val, n.val));
p.next = valNode;
valNode.next = n;
p = n
}
current = current.next;
}
return head;
}
// 求最大公约数
function greatestCommonDivisor(a: number, b: number): number {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
}
class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
let listTag1 = new ListNode(1);
let listTag2 = new ListNode(3);
let listTag3 = new ListNode(4);
let listTag4 = new ListNode(7);
let listTag5 = new ListNode(1);
let listTag6 = new ListNode(2);
let listTag7 = new ListNode(6);
listTag1.next = listTag2;
listTag2.next = listTag3;
listTag3.next = listTag4;
listTag4.next = listTag5;
listTag5.next = listTag6;
listTag6.next = listTag7;
console.log(insertGreatestCommonDivisors(listTag1));
// @lc code=end
Loading...
