链表逆序输出两种方法,第一种利用递归加回溯,第二种利用辅助栈。
感觉很久不写算法题了,手感都很陌生了,但是这一道题还是很能体现出来递归和回溯的魅力
1.递归
`def reversePrint(head):
return revrsePrint(head.next)+[head.val] if head else []`
例如[1,2,3]
这样一直递归到尾结点,再回溯,依次从尾到头再返回[]、[]+[3]、[3]+[2]、[3,2]+[1]。
2.利用辅助栈
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
res=[]
while head:
res.append(head.val)
head=head.next
res.reverse()
return res
还是太简单了