输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
思路:
一、使用栈来解决问题
思路上来说,我们是从头到尾遍历的链表,却要从尾到头来打印,这就是后进先出,符合栈的结构
所以在遍历链表的时候,每遍历到一个元素,就把该元素的值放到栈中,那在输出的时候,就会从尾到头的打印数据了。
/**
* Definition for singly-linked list.
* 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)
* }
* }
*/
function reversePrint(head: ListNode | null): number[] {
const res: number[] = [];
if(head === null) return res;
while(head !== null){
res.unshift(head.val);
head = head.next;
}
return res
};
二、使用递归
递归本质上也是一个栈结构,要实现反过来输出链表,每访问到一个节点的时候,就先去递归输出后面的节点,再输出该节点自身,这样链表的输出结果就反过来了。
/**
* Definition for singly-linked list.
* 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)
* }
* }
*/
function reversePrint(head: ListNode | null): number[] {
let res: number[] = [];
if (head === null) return [];
res = reversePrint(head.next)
res.push(head.val)
return res
};