从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:0 <= 链表长度 <= 10000
来源:力扣
思路:
循环遍历,利用数组提供的 unshift 方法来实现
递归遍历,走到链表最后一个元素时开始 push
这题我没有用reverse()方法,用的是unshift()
代码如下:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {number[]}
*/
var reversePrint = function(head) {
var arr=[];
while(head!=null){
arr.unshift(head.val);
head=head.next;
}
return arr;
};
看的其他人用的reverse()方法写的代码:
var reversePrint = function (head) {
if (head === null) return []
const res = []
while (head) {
res.push(head.val)
head = head.next
}
return res.reverse()
}
作者:rinnyushinndesu
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/js-3chong-jie-ti-by-rinnyushinndesu/