题目
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
思路
创建一个数组,遍历链表,依次将值unshift进数组
实现
// class ListNode {
// * val: number
// * next: ListNode | null
// * constructor(val?: number, next?: ListNode | null) {
// * this.val = (val===undefined ? 0 : val)
// * this.next = (next===undefined ? null : next)
// * }
// * }
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param head ListNode类
* @return int整型一维数组
*/
export function printListFromTailToHead(head: ListNode): number[] {
// write code here
let arr: number[] = []
while(head) {
arr.unshift(head.val)
head = head.next
}
return arr
}