题意
输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。
思路
用数组顺序保存链表的值,数组逆序输出。
代码
class Solution:
def printListFromTailToHead(self , listNode: ListNode) -> List[int]:
# write code here
if listNode==None:
return []
else:
s=[listNode.val]
p=listNode.next
while p!=None:
s.append(p.val)
p=p.next
return s[::-1]
优化:
class Solution:
def printListFromTailToHead(self , listNode: ListNode) -> List[int]:
# write code here
s = []
while listNode:
s.append(listNode.val)
listNode = listNode.next
return s[::-1]