剑指offer JS题解 (3)从尾到头打印链表

题目描述

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

示例

输入:head = [1,3,2]
输出:[2,3,1]

解题思路

可以用栈存下节点的值,JS中有反向的栈方法可以使用(shift和unshift),unshift可以从数组头部插入元素。

Code

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function printListFromTailToHead(head)
{
    // write code here
    const res=[];
    let pNode=head;
    while(pNode!=null){
        res.unshift(pNode.val);
        pNode=pNode.next;
    }
    return res;
}

运行环境:JavaScript (V8 6.0.0)
运行时间:28ms
占用内存:13420k

猜你喜欢

转载自blog.csdn.net/qq_40340478/article/details/106131037
今日推荐