剑指offer_06_从尾到头打印链表【javascript】

66 阅读1分钟

题目

驶入一个链表的头节点,从尾到头反过来打印出每个节点的值。链表节点定义如下:

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

题解一:辅助栈

var reversePrint = function(head) {
    let stack = [];
    // let res = [];
    while (head !== null) {
        stack.push(head.val);
        head = head.next;
    }
    // while (stack.length) {
    //     res.push(stack.pop());
    // }
    // return res;
    return stack.reverse();
};

复杂度分析

  • 时间复杂度: O(N)
  • 空间复杂度:O(N)

题解二:递归法

var reversePrint = function(head) {
  let arr = [];
  const revList = (head) => {
      if (head !== null) {
          revList(head.next);
          arr.push(head.val);
      }
  }
  revList(head);
  return arr;
};

复杂度分析

  • 时间复杂度:O(N)
  • 空间复杂度:O(N)