题目:从尾到头打印链表
题目描述:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
python实现思路:
python中的数据类型-列表中,append()方法是在列表的尾部插入元素,insert()方法可以指定位置插入数据到列表中,所以可以从头到尾遍历链表,将每次遍历的结果都插入到列表的第0个元素的位置,即得到一个从尾到头的顺序的列表。
#定义链表的结点类
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
arraylist = []
head = listNode
while head:
arraylist.insert(0,head.val)
head = head.next
return arraylist
#测试一下
if __name__ == '__main__':
su = Solution()
#建立一个链表用于测试程序
head = ListNode(1)
phead = head
for i in range(2,6):
node = ListNode(i)
head.next = node
head = head.next
res = su.printListFromTailToHead(phead)
print(res)