大家一起加油,我喜欢分专栏将知识打碎成一份一份小知识点,一篇文章只说一个知识点,因此每篇文章篇幅较短,希望大家不要介意。如有需要可以查看专栏看看是否有该文章中涉及到的知识点进行讲解的文章,如果大家觉得有帮助,希望大家三连支持一下。 |
推荐阅读
题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
代码实现
方式1
const head = {
val: 1,
next: {
val: 3,
next: {
val: 2,
next: null,
},
},
};
var reversePrint = function(head) {
if (head) {
if (head.next) {
return [...reversePrint(head.next), head.val]
}
return [head.val]
}
return []
};
console.log(reversePrint(head));
方式2
const head = {
val: 1,
next: {
val: 3,
next: {
val: 2,
next: null,
},
},
};
var reversePrint = function(head) {
const arr = [];
while (head) {
arr.unshift(head.val);
head = head.next;
}
return arr;
};
console.log(reversePrint(head));
![](https://i-blog.csdnimg.cn/blog_migrate/c181597133349ca919939b3360530f7c.png)