【剑指 Offer 06】从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 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
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值