描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
tags: recursive
思路
- 利用栈来存储,出栈即可
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
res = []
while head:
res.append(head.val)
head = head.next
return res[::-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