Print linked list from end to beginning
Enter the head node of a linked list, and return the value of each node from the end to the beginning (return with an array).
Example 1:
Input: head = [1,3,2]
Output: [2,3,1]
Limit: 0 <= Link list length <= 10000
Source: Likou
Idea:
Loop traversal, use the unshift method provided by the array to achieve
recursive traversal, and start pushing when it reaches the last element of the linked list
For this question, I did not use the reverse() method, but the unshift()
code is as follows:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {number[]}
*/
var reversePrint = function(head) {
var arr=[];
while(head!=null){
arr.unshift(head.val);
head=head.next;
}
return arr;
};
Look at the code written by other people using the reverse() method:
var reversePrint = function (head) {
if (head === null) return []
const res = []
while (head) {
res.push(head.val)
head = head.next
}
return res.reverse()
}
作者:rinnyushinndesu
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/js-3chong-jie-ti-by-rinnyushinndesu/