剑指Offer 06. 从尾到头打印链表(Easy)
题解
思路
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
### 1009 递归(152 ms,22.5 MB)
def reversePrint(self, head: ListNode) -> List[int]:
return self.reversePrint(head.next) + [head.val] if head else []
### 1009 辅助栈(52 ms,14.8 MB)
def reversePrint(self, head: ListNode) -> List[int]:
stack = []
while head:
stack.append(head.val)
head = head.next
return stack[::-1]