leedcode 从尾到头打印 链表中字符串

class ListNode:
def init(self,x):
self.val = x
self.next = None

class Solution:
def reversePrint(self,head:List) -> List[int]:
return self.reversePrint(head.next) + [head.val] if head else []

关于递归的思考

1.需要设置结束条件 , 在这个例子中 是 head 是否为空
2.递归中,设置的存储变量一直在 例如 例子中 [ ] (变量)这个list中的元素, 从递归的第一次开始就保存,没有释放
3.接下来 是递归的推进 , 这个例子中使用head.next

  1. 递归最后一步,回溯 (没有太懂这个)(返回 当前 list + 当前节点值 [head.val] ;)

非递归方式

就是依次遍历链表,放到一个list中 ,然后 在是用 【::- 1】倒序
(python 的切片都是 左闭右开 的取值 )

你可能感兴趣的:(leedcode 从尾到头打印 链表中字符串)