LeetCode Notes: Print linked list from end to beginning
Question
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]
Solution
Analysis:
Traverse this linked list directly and take the value of each node and stuff it into the first place of the array.
Code:
/**
  * Definition for singly-linked list.
  * function ListNode(val) {
  * this.val = val;
  * this.next = null;
  *}
  */
/**
  * @param {ListNode} head
  * @return {number[]}
  */
var reversePrint = function(head) {
     // Store the result
     const result = []
     // Traverse to the end of the linked list
     while(head != null){
         result.unshift(head.val)
         head = head.next
     }
     return result
};

Comments