题解
/*** 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 addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {// 头节点 当前节点let head = null; let target = null;// 累加值 传递到下一次循环let carry = 0;while (l1 || l2) {let val1 = l1 && l1.val || 0;let val2 = l2 && l2.val || 0;let sum = val1 + val2 + carry;// 判断是否第一次if (!head) {head = target = new ListNode(sum % 10);} else {target.next = new ListNode(sum % 10);target = target.next;}// 重置累加值carry = Math.floor(sum / 10);if (l1) {l1 = l1.next;}if (l2) {l2 = l2.next;}}// 此时如果carry > 0 说明要加一位 也就是新加一个节点if (carry > 0) {target.next = new ListNode(carry);}return head;};
相似题目
思路
解法与上题相似,不过反过来了, 我们可以通过两个栈(stack)来记录遍历两条链表的值,
通过一个max变量 比较两个栈的大小 取最大值进行遍历,从尾部构建出整个链表。
代码
/**
* 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 addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
let target = null;
let a = null;
let stack1 = [], stack2 = [];
while (l1) {
stack1.push(l1.val);
l1 = l1.next;
}
while (l2) {
stack2.push(l2.val);
l2 = l2.next;
}
let carry = 0;
let arr = [];
let sum = 0;
let max = Math.max(stack1.length, stack2.length);
for (let i = 0; i < max; i++) {
let val1 = stack1.pop() || 0;
let val2 = stack2.pop() || 0;
sum = val1 + val2 + carry;
a = new ListNode(sum % 10);
a.next = target;
target = a;
carry = Math.floor(sum / 10);
}
let x = null;
if (carry > 0) {
x = new ListNode(carry);
x.next = target;
console.log(x.val);
}
console.log(target.val);
return target ? carry ? x : target : null;
};

