前往此题

辅助栈法

思路很简单,通过辅助栈temp将所有节点放入其中。然后遍历整个栈从末尾开始放入最终答案res中即可。

代码

# 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]:
        if not head: return []
        temp = []
        res = []
        while head:
            temp.append(head.val)
            head = head.next
        
        while temp:
            res.append(temp.pop())
        return res

递归法

先走至链表末端,回溯时依次将节点值加入列表 ,这样就可以实现链表值的倒序输出。

代码

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