从尾到头打印链表-JavaScript-剑指offer

从尾到头打印链表

http://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035

【JavaScript】从尾到头打印链表-剑指offer

题目描述

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

解法 1: 栈

题目要求的是从尾到头。这种“后进先出”的访问顺序,自然想到了用栈。

时间复杂度 O(N),空间复杂度 O(N)。

// ac地址:https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
// 原文地址:https://xxoo521.com/2019-12-21-da-yin-lian-biao/

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/

/**
 * @param {ListNode} head
 * @return {any[]}
 */
function printListFromTailToHead(head) {
    const stack = [];
    let node = head;
    while (node) {
        stack.push(node.val);
        node = node.next;
    }

    const reverse = [];
    while (stack.length) {
        reverse.push(stack.pop());
    }

    return reverse;
}

发现后半段出栈的逻辑,其实就是将数组reverse反转。因此,借助 javascript 的 api,更优雅的写法如下:

// ac地址:https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
// 原文地址:https://xxoo521.com/2019-12-21-da-yin-lian-biao/

/**
 * @param {ListNode} head
 * @return {any[]}
 */
function printListFromTailToHead(head) {
    const stack = [];
    let node = head;
    while (node) {
        stack.push(node.val);
        node = node.next;
    }

    return stack.reverse();
}

专注前端与算法的系列干货分享,欢迎关注(¬‿¬):
「微信公众号:心谭博客」| xxoo521.com | GitHub

全部评论
unshift()方法直接在前面插入
5
送花
回复
分享
发布于 2020-01-19 14:33

相关推荐

7 1 评论
分享
牛客网
牛客企业服务