输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例:

输入:head = [1,3,2] 输出:[2,3,1]  

限制:0 <= 链表长度 <= 10000

解:

方法一遍历链表使用unshift将元素添加到数组头部
/**
 * 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 === null) return []
   let result = []
   while(head){
       result.unshift(head.val)
       head = head.next
   }
   return result
};

方法二反转链表遍历链表将元素push到数组
/**
 * 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 === null) return []
   head = reverseList(head)
   let result = []
   while(head){
       result.push(head.val)
       head = head.next
   }
   return result
};

function reverseList(head){
    let next;
    let pre;
    while(head){
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
    }
    return pre
}