题目描述
输入一个链表,按链表值从尾到头的顺序返回一个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
if not listNode:
return []
stack=[]
res=[]
while listNode:
stack.append(listNode.val)
listNode=listNode.next
while stack:
res.append(stack.pop())
return res
测试用例
if __name__ == '__main__':
s=Solution()
head=ListNode(1)
phead=head
for i in range(2,8):
node = ListNode(i)
phead.next = node
phead = phead.next
res = s.printListFromTailToHead(head)
print(res)