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

题目描述:输入一个链表,按链表从尾到头的顺序返回一个 ArrayList。

题目描述

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

解法 1: 栈

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

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

// ac地址:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
// 原文地址:https://xxoo521.com/2019-12-21-da-yin-lian-biao/

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
var reversePrint = function(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 {number[]}
 */
var reversePrint = function(head) {
    const stack = [];
    let node = head;
    while (node) {
        stack.push(node.val);
        node = node.next;
    }
    return stack.reverse();
};

更多资料

# ,
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×