当前位置: 代码迷 >> 综合 >> 剑指offer JZ3 - 从尾到头打印链表 - JavaScript
  详细解决方案

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

热度:46   发布时间:2024-02-11 13:53:44.0

1、题目描述

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

2、解题思路

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

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

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;    //上述步骤可以直接改写成:return stack.reverse();
}
  相关解决方案