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

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

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

    答案:头插法

    1

    1. function ListNode(val) {
    2. this.val = val;
    3. this.next = null;
    4. }
    5. const head = new ListNode()
    6. const head1 = new ListNode()
    7. const head2 = new ListNode()
    8. const head3 = new ListNode()
    9. Object.assign(head,{val:undefined,next:head1})
    10. Object.assign(head1,{val:1,next:head2})
    11. Object.assign(head2,{val:2,next:head3})
    12. Object.assign(head3,{val:3,next:null})
    13. var reversePrint = function(head) {
    14. const res = []
    15. function recur (ListNode){
    16. if(ListNode.next===null) {
    17. res.push(ListNode.val)
    18. return
    19. }
    20. recur(ListNode.next)
    21. if(ListNode.val)
    22. res.push(ListNode.val)
    23. }
    24. recur(head)
    25. return res
    26. }
    27. reversePrint(head)

    2

    var reversePrint = function (head) {
      if (head === null) return []
      const res = []
      while (head) {
        res.push(head.val)
        head = head.next
      }
      return res.reverse()
    }
    

    3

    var reversePrint = function(head) {
         if (head === null) return []
        const res=[]
        while(head){
            res.unshift(head.val)
            head=head.next
        }
        return res
    }
    

    4

    // 首先将链表反转
    function reverseLink(head) {
        if (head === null || head.next === null) return head
        let p = head.next
        head.next = null
        let tmp = null
        while (p !== null) {
            tmp = p.next // tmp 指针前进(保存下一个指针信息)
            p.next = head // 指针反转
            head = p // head 指针前进
            p = tmp // p 指针前进
        }
        return head
    }
    //再顺序输出链表