输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
res = self.getValue(head)
# print(res)
return res
def getValue(self,head:ListNode):
if( head is None ):
return []
else:
# 获取返回的列表,从最后一个开始返回,进行递归
res = self.getValue(head.next)
# 添加该层的值
res.append(head.val)
return res
本文介绍了一种使用递归算法从尾到头逆序打印链表节点值的方法。通过定义链表节点类和解决方案类,实现了一个reversePrint函数,该函数接收链表头节点作为参数,并返回一个包含逆序节点值的数组。
4937

被折叠的 条评论
为什么被折叠?



