You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请帮忙解析单链表实现中的reverse()函数逻辑

单链表reverse()函数逐行解析

先贴出完整的单链表实现代码:

class LinkedList {
  constructor(value) {
    this.head = {
      value: value,
      next: null,
    };
    this.tail = this.head;
    this.length = 1;
  }

  append(value) {
    const newNode = {
      value: value,
      next: null,
    };
    this.tail.next = newNode;
    this.tail = newNode;
    this.length++;
    return this;
  }

  prepend(value) {
    const newNode = {
      value: value,
      next: null,
    };
    newNode.next = this.head;
    this.head = newNode;
    this.length++;
    return this;
  }

  reverse() {
    if (!this.head.next) {
      return this.head;
    }
    let first = this.head;
    this.tail = this.head;
    let second = first.next;

    while (second) {
      const temp = second.next; //third
      second.next = first;
      first = second;
      second = temp;
    }

    this.head.next = null;
    this.head = first;
    return this.printList();
  }
}

下面逐行拆解reverse()函数的逻辑:

1. 边界条件处理

if (!this.head.next) {
  return this.head;
}

如果链表只有一个节点(头节点的next指向null),反转后链表结构完全不变,直接返回头节点即可,无需后续操作。

2. 初始化反转变量

let first = this.head;
this.tail = this.head;
let second = first.next;
  • first:初始指向原链表的头节点,后续会逐步移动到链表末尾,最终成为新的头节点
  • this.tail = this.head:反转后,原链表的头节点会变成新链表的尾节点,所以先把链表的tail指针指向原头节点
  • second:初始指向原链表的第二个节点,是当前要修改指针方向的节点

3. 核心反转循环

while (second) {
  const temp = second.next; //third
  second.next = first;
  first = second;
  second = temp;
}

这个循环是反转的核心,用三个节点的视角理解(first、second、temp即原second.next):

  • const temp = second.next:先把second的下一个节点存到temp里——因为接下来要修改second.next,如果不提前保存,会丢失后续的链表节点,导致遍历中断
  • second.next = first:把second的next指针指向first,这一步直接反转了两个节点的指向关系(原本first → second,现在变成second → first)
  • first = second:把first指针往前挪,指向当前的second——下一轮循环要处理新的second的指针方向
  • second = temp:把second指针往前挪,指向之前存的temp(原second的下一个节点),开启下一轮反转

循环会一直执行,直到second为null(也就是遍历完了整个链表)。

4. 收尾调整指针

this.head.next = null;
this.head = first;
return this.printList();
  • this.head.next = null:原链表的头节点现在是新链表的尾节点,尾节点的next必须指向null,所以这里把它的next设为空
  • this.head = first:循环结束后,first已经移动到了原链表的尾节点,现在把它设为新链表的头节点
  • return this.printList():返回打印链表的结果,方便直观查看反转后的链表结构

时间复杂度说明

该reverse()函数的时间复杂度为O(n),其中n是链表的节点数量——因为循环会遍历链表的每一个节点一次,没有嵌套循环,所以时间复杂度是线性的。

内容的提问来源于stack exchange,提问作者AbdelrahmanMurad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 12:56:13