Topic describes

Enter the head node of a linked list and return the value of each node from end to end (as an array). Example 1: input: head = [1,3,2] output: [2,3,1] limit: 0 <= linked list length <= 10000

1. Traversal

Traverses the list into an array, entering the array in reverse order

Example code 1:

def reversePrint(head: helper.ListNode) :
    result = []
    while head is not None:
        result.append(head.val)
        head = head.next
    return result[::-1]
Copy the code

Solution idea 2: Auxiliary stack method

Iterate through the list and put it on a stack. By the nature of stack FILO, the output stack is a linked list in reverse order

Example code 2:

def reversePrint(head: helper.ListNode) :
    stack = []
    while head is not None:
        stack.append(head.val)
        head = head.next

    res = []
    while len(stack) > 0:
        res.append(stack.pop())
    return res

Copy the code

Solution 3: Recursive backtracking

Recursively traverses the list, returning the array of last recursion and the current item when backtracking

Example code 3:

def reversePrint(head: helper.ListNode) :
    if head is None:
        return []
    else:
        return reversePrint(head.next) + [head.val]
Copy the code