SOURCE

class ListNode {
  constructor(val, next = null) {
    this.val = val;
    this.next = next;
  }
}

// 文件浏览历史链表操作类
class FileHistoryLinkList {
  constructor() {
    this.head = null;
  }

  addNode(val) {
    const newNode = new ListNode(val);
    if (!this.head) {
      this.head = newNode;
      return;
    }
    let cur = this.head;
    while (cur.next) {
      cur = cur.next;
    }
    cur.next = newNode;
  }

  // 迭代反转链表(原地反转,最优空间)
  reverseByIterate() {
    let prev = null;
    let cur = this.head;
    while (cur) {
      const nextTemp = cur.next;
      cur.next = prev;
      prev = cur;
      cur = nextTemp;
    }
    // 更新链表头为反转后的头节点
    this.head = prev;
    return this;
  }

  // 递归反转链表
  reverseRecur(node) {
    if (!node || !node.next) return node;
    const newHead = this.#reverseRecur(node.next);
    node.next.next = node;
    node.next = null;
    return newHead;
  }
  reverseByRecursion() {
    this.head = this.#reverseRecur(this.head);
    return this;
  }

  // 打印链表,输出访问顺序(用于查看浏览历史)
  printList() {
    const res = [];
    let cur = this.head;
    while (cur) {
      res.push(cur.val);
      cur = cur.next;
    }
    console.log("浏览历史顺序:", res.join(" -> "));
    return res;
  }
}
console 命令行工具 X clear

                    
>
console