剑指offer从尾到头打印链表python

题目描述

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

思路

遍历链表,把结构保存在list里面,然后把list逆序输出

代码

 1 # -*- coding:utf-8 -*-
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     # 返回从尾部到头部的列表值序列,例如[1,2,3]
 9     def printListFromTailToHead(self, listNode):
10         if not listNode:
11             return []
12         my_list = []
13         current = listNode
14         while current:
15             my_list.append(current.val)
16             current = current.next
17         my_list.reverse()
18         return my_list
19     
 
原文地址:https://www.cnblogs.com/wangzhihang/p/11778219.html