剑指Offer——从尾到头打印链表(JS实现)

140 阅读1分钟

题目描述

解题思路

  • 首先遍历链表,将链表中的每一个值都存在一个数组中。
  • 然后倒叙遍历这个数组,最后返回

实现代码(遍历+倒序)

var reversePrint = function(head) {
    const arr = [];
    while (head) {
        arr.push(head.val);
        head = head.next;
    }

    const result = [];
    const len = arr.length;
    for (let i = 0; i < len;i++) {
        result.push(arr.pop());
    }

    return result;

};

反转链表实现法

var reversePrint = function(head) {
    // 从尾到头打印链表
    let cur = head;
    let pre = null;
    while (cur) {
        let next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    const res = [];
    while (pre) {
        res.push(pre.val);
        pre = pre.next;
    }
    return res;
};

通过反转链表来实现其实更加好~