剑指 Offer 06. 从尾到头打印链表

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

tags: recursive

思路

  1. 利用栈来存储,出栈即可
class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        res = []
        while head:
            res.append(head.val)
            head = head.next
        return res[::-1]
  1. 递归
class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        def helper(node):
            if not node:
                return
            helper(node.next)
            res.append(node.val)
        res = []
        helper(head)
        return res
原文地址:https://www.cnblogs.com/fengcnblogs/p/13509762.html