【剑指offer6:从尾到头打印链表】【力扣刷题】【Python】

方法一堆栈

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        stack=[]
        if not head:
           return []
        while head:
            stack.append(head.val)
            head=head.next
        return stack[::-1]

方法二:递归

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        while head:
            return self.reversePrint(head.next)+[head.val] 
        return []

你可能感兴趣的:(剑指offer)