93 lines
2.3 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const addTwoNumbers = function (l1, l2) {
};
/*
直接遍历两个链表,列表的头节点代表的是各位,后一个节点代表的是十位,以此类推,所以只需定义一个
变量表示进位即可把计算好的结果拼接成l3即可
*/
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
function f1(l1, l2) {
let carry = 0; // 进位
const dummyHead = new ListNode(0); // 哑节点,用于返回结果
let current = dummyHead; // 当前节点,用于构建求和之和的链表
// 遍历两个链表,直到,链表都为空,并且没有进位(只要有节点或者进位不等于0就需要创建新的求和节点)
while (l1 !== null || l2 !== null || carry !== 0) {
let sum = carry;
if (l1) {
sum += l1.val;
l1 = l1.next;
}
if (l2) {
sum += l2.val;
l2 = l2.next;
}
// 根据sum,计算出current节点的值和进位值
current.next = new ListNode(sum % 10);
current = current.next;
carry = Math.floor(sum / 10);
}
return dummyHead.next;
}
/*
将链表转换成字符串数字,之后把字符串数字相加,最后处理成一个新的列表
*/
function f2(l1, l2) {
let numStr1 = '';
let numStr2 = '';
// 将第一个链表反转并拼接为字符串
let cur1 = l1;
while (cur1 !== null) {
numStr1 = cur1.val + numStr1;
cur1 = cur1.next;
}
// 将第二个链表反转并拼接为字符串
let cur2 = l2;
while (cur2 !== null) {
numStr2 = cur2.val + numStr2;
cur2 = cur2.next;
}
// 将拼接的字符串转为数字并进行加法运算
const sum = BigInt(numStr1) + BigInt(numStr2); // 使用 BigInt 处理大数字
// 将求和结果转换为字符串
const sumStr = sum.toString();
// 将求和结果转换为链表
const dummyHead = new ListNode(0);
let current = dummyHead;
for (let i = sumStr.length - 1; i >= 0; i--) {
current.next = new ListNode(Number(sumStr[i]));
current = current.next;
}
return dummyHead.next; // 返回结果链表的头节点
}