剑指offer06:从尾到头打印链表 python
题目描述
解法
非递归,将链表的值从头到尾输入到list,再反转list
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
if head is None:
return []
node = head
res = []
while node:
res.append(node.val)
node = node.next
return res[::-1]
时间复杂度O(n),空间复杂度 O(n)
递归
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
return self.reversePrint(head.next) + [head.val] if head else []
时间复杂度O(n),空间复杂度 O(n),其实时间复杂度和空间复杂度都没有降低。。。就是看起来好像简单了一些。。。
思考与感想
这道题没啥思考和感想。。。。。。。继续加油!!!