一:写出链表构造函数
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 arr1 = [2, 4, 3];
let arr2 = [5, 6, 4];
// 根据数组构建链表
function makeList(arr: Array<any>): ListNode | null {
let head = new ListNode();
let tmp = head;
for (let item of arr) {
tmp.next = new ListNode(item);
tmp = tmp.next;
}
return head.next;
}
let l1 = makeList(arr1);
let l2 = makeList(arr2);
练习题:leedcode第二题两数之和(难度中等)
写代码注意两点:
- 空指针加判断;
- 进位时候的处理,比如三位数相加可能成为四位数
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 arr1 = [2, 4, 3];
let arr2 = [5, 6, 4];
// 根据数组构建链表
function makeList(arr: Array<any>): ListNode | null {
let head = new ListNode();
let tmp = head;
for (let item of arr) {
tmp.next = new ListNode(item);
tmp = tmp.next;
}
return head.next;
}
let l1 = makeList(arr1);
let l2 = makeList(arr2);
function addTwoNumbers(
l1: ListNode | null,
l2: ListNode | null
): ListNode | null {
//声明结果的第一个节点
let head = new ListNode();
// 声明指针,每次循环都可以指向链表中下一个节点
let tmp = head;
let tmp1 = l1;
let tmp2 = l2;
// carry表示进位
let carry = 0;
while (tmp1 || tmp2) {
let val1 = tmp1?.val || 0;
let val2 = tmp2?.val || 0;
let sum = val1 + val2 + carry;
let nextVal = sum % 10;
// 存储进位多少
carry = Math.floor(sum / 10);
tmp.next = new ListNode(nextVal);
tmp = tmp.next;
tmp1 = tmp1?.next || null;
tmp2 = tmp2?.next || null;
}
// 遍历完成用以后,如果进位大于0,追加到末尾,这个容易漏掉
if (carry) {
tmp.next = new ListNode(carry);
}
return head.next;
}
let res = addTwoNumbers(l1, l2);
console.log(res);