题目介绍
输入一个链表,从尾到头反过来打印出每个节点的值。
链表节点定义如下:
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
算法解析
递归
n次找到最后的链表节点,n次返回。
时间复杂度O(n)。
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
if not listNode:
return []
res = self.printListFromTailToHead(listNode.next)
res.append(listNode.val)
return res
循环
顺序将链表值存在列表中,最后将列表翻转即可。
时间复杂度O(n)。
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
if not listNode:
return []
res = []
while listNode:
res.append(listNode.val)
listNode = listNode.next
return res[::-1]