每日算法 从头到尾打印链表 3

版权声明:我是小仙女 转载要告诉小仙女哦 https://blog.csdn.net/qq_40210472/article/details/88681971

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

使用思路为:遍历链表,将得到的每个节点的值插入到需返回的列表的头部。

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        l = []
        head = listNode
        while head:
            l.insert(0, head.val)
            print head.val
            head = head.next
        return l

    

猜你喜欢

转载自blog.csdn.net/qq_40210472/article/details/88681971