Topic describes

Enter the head node of a linked list and return the value of each node from end to end (as an array).

The subject sample

Enter: head = [1.3.2] output: [2.3.1]
Copy the code

title

Each element in a linked list consists of a node that stores the element itself (the value of the element) and a reference (pointer or link) to the next element

The easiest way to solve this problem is to iterate through the list, storing each element in a temporary array that can be reversed on output, or unshift the array.

Code implementation

/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {number[]} */ const reverseLinkedList = function(head) { const results = []; let current = head; // current ! = null and current! == null || current ! == undefined equivalent while(current! = null) { results.unshift(current.val) current = current.next } return results }Copy the code

Title source

Print the linked list from end to end

Reference books

Learning JavaScript Data Structures and Algorithms (3rd edition)