链接: 原文链接.
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 自己写的,调用insert,比较费时间。 # def reversePrint(self, head: ListNode) -> List[int]: # lis = [] # while head: # lis.insert(0, head.val) # head = head.next # return lis # 大佬写的,用append然后,直接切片逆序输出,这样的话速度更快 # 字符串[开始索引:结束索引:步长] def reversePrint(self, head: ListNode) -> List[int]: stack = [] while head: stack.append(head.val) head = head.next return stack[::-1]