描述
题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
Solution 递归
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
if not head: return []
res = []
def backtrack(head):
if not head: return
backtrack(head.next)
res.append(head.val)
backtrack(head)
return res
Solution 迭代
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
res = []
head = listNode
while head != None:
res.append(head.val)
head = head.next
return res[::-1]