题干
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
解题
解题一、reverseApi
/**
* 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 []
let res = []
while(head){
res.push(head.val)
head = head.next
}
res = res.reverse()
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 []
var arr = reversePrint(head.next);
arr.push(head.val)
return arr;
};
递归方法的时间复杂度取决于O(nf(n)),这里迭代的f(n)的复杂度为O(1),整体复杂度为O(n)
reverseApi方法复杂度也为O(n)