题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
- 用列表保存
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
temp = []
p = listNode
while(p):
temp.append(p.val)
p = p.next
return temp[::-1]
- 递归
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
ans = []
def printlistnode(listNode):
if listNode:
printlistnode(listNode.next)
ans.append(listNode.val)
printlistnode(listNode)
return ans
本文介绍了一种使用链表数据结构的算法,该算法能够将链表中的元素从尾部到头部进行逆序输出。通过两种方法实现:迭代法和递归法。迭代法中,先遍历链表并将每个节点的值存入列表,最后反转列表;递归法则利用函数调用栈的特性,先到达链表尾部再逐层返回并收集节点值。
2499

被折叠的 条评论
为什么被折叠?



