- 刚接触链表题目的时候都不知道如何调试,看着 leetcode 给出的输入输出一头雾水。
为什么链表题目的输入是一个数组,输出也是一个数组呢?
- 其实很简单,输入是将一个数组转化成一个链表,并将头节点返回给你。
输出则是通过你返回的头节点遍历这个链表,将其转化成数组。
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
- 这个代码是创建一个链表的单节点,那么我们要怎么样处理,才能将数组转化成链表呢
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
function SingleList(arr) {
let prev = new ListNode(0, null);
let head = prev;
arr.forEach((element) => {
prev.next = new ListNode(element, null);
prev = prev.next;
});
return head.next;
}
function SingleListDisplay(head) {
const ans = [];
while (head) {
ans.push(head.val);
head = head.next;
}
return ans;
}
- 网上有很多生成链表的代码,但是都太臃肿了,我们在调试链表题的时候并不需要有那么多的方法,我们只需要一个最小模型即可。
- 从数组转链表的过程中,我们也可以学到一种链表的思想,就是创建一个虚拟的头节点 head,然后返回时,返回 head.next 就返回了真正的头节点。
- leetcode 两数相加 leetcode.cn/problems/ad…
var addTwoNumbers = function (l1, l2) {
let addOne = 0;
let sum = new ListNode(0);
let head = sum;
while (addOne || l1 || l2) {
let v1 = l1 !== null ? l1.val : 0;
let v2 = l2 !== null ? l2.val : 0;
let r1 = v1 + v2 + addOne;
addOne = r1 >= 10 ? 1 : 0;
sum.next = new ListNode(r1 % 10);
sum = sum.next;
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
return head.next;
};
const head1 = SingleList([2, 4, 3]);
const head2 = SingleList([5, 6, 4]);
console.log(SingleListDisplay(addTwoNumbers(head1, head2)));
- leetcode 反转链表 leetcode.cn/problems/fa…
var reverseList = function (head) {
let cur = head;
let pre = null;
while (cur) {
let tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
};
const head1 = SingleList([2, 4, 3]);
console.log(SingleListDisplay(reverseList(head1)));