class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
# 方法一 使用栈
if not listNode:
return []
temp = []
result = []
while listNode:
temp.append(listNode.val) # 进栈
listNode = listNode.next
while temp:
result.append(temp.pop()) # 出栈
return result
# 方法二 使用递归
result = []
def solutions(Node):
if Node:
solutions(Node.next)
result.append(Node.val)
solutions(listNode)
return result
# 方法三 使用从头到尾遍历,逆序输出
result = []
while listNode:
result.append(listNode.val)
listNode = listNode.next
return result[::-1]