# -*-coding:utf-8 -*-
'''
题目
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
思路
可以先顺序遍历链表元素,再反向输出元素
'''
"""
Author:
Yao Zhian
Blog:
https://cuijiahua.com/blog/2017/11/basis_3.html
Modify:
2020-01-18
"""
def createlistNode(array):
"""
创建初始链表
Parameters:
无
Returns:
listNode - 创建后的链表
"""
if len(array) == 0:
listNode = None
elif len(array) == 1:
listNode = ListNode(array[0])
else:
listNode1 = ListNode(array[0])
listNode = listNode1
for i in range(1,len(array)):
listNode1.next = ListNode(array[i])
listNode1 = listNode1.next
return listNode
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
ArrayList = []
while listNode != None: # 顺序遍历链表,将遍历的结果保存在ArrayList列表中
ArrayList.append(listNode.val)
listNode = listNode.next
return ArrayList[::-1] # 反向输出ArrayList列表
if __name__ == '__main__':
array = [64, 0, 34, 12]
listNode = createlistNode(array)
S = Solution()
print(S.printListFromTailToHead(listNode))