输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
方法一:递归方法,每次都是head.next+head.val
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
if head:
return self.reversePrint(head.next)+[head.val]
else:
return []
方法二:转化为list后再逆向输出
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
a=[]
while head:
a.append(head.val)
head=head.next
return a[::-1]