题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
链表的逆序输出,但是不用对链表本身进行倒置,所以就简单地读出所有元素然后逆序返回即可,也就是栈的思想,也可以用Python中列表的倒序写法,代码如下:
class Solution(object):
def reversePrint(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
res=[]
while head != None:
res.append(head.val)
head=head.next
return res[::-1]
之前说用了栈的思想,那么也可以用递归来实现,先递归到链表尾,然后回溯时将每个数加入列表中,这样列表可以直接返回,代码如下:
class Solution(object):
def reversePrint(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
if head == None:
return []
res=self.reversePrint(head.next)
res.append(head.val)
return res