链表-3-从尾到头打印链表

本文介绍了一种使用链表数据结构的算法,该算法能够将链表中的元素从尾部到头部进行逆序输出。通过两种方法实现:迭代法和递归法。迭代法中,先遍历链表并将每个节点的值存入列表,最后反转列表;递归法则利用函数调用栈的特性,先到达链表尾部再逐层返回并收集节点值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

输入一个链表,按链表从尾到头的顺序返回一个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

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值