06.从尾到头打印链表
解法一:反转链表
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {number[]}
*/
var reversePrint = function(head) {
// 反转链表后依次打印
if(!head) return []
if(!head.next) return [head.val]
let prev = null
let curr = head
let temp = null
while(curr) {
temp = curr.next
curr.next = prev
prev = curr
curr = temp
}
let res = []
while(prev) {
res.push(prev.val)
prev = prev.next
}
return res
};
解法二:递归
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {number[]}
*/
var reversePrint = function(head) {
// 递归
if(!head) return []
return !head.next ? [head.val] : reversePrint(head.next).concat(head.val)
};