Linked List

链表

线性结构入门时间 访问 O(n) / 插入 O(1)空间 O(n)

结点通过指针串联。插入删除不搬移,但无法按下标跳跃,只能顺着 next 走。

动画

head
4
9
1
null

单向链表:每个结点保存值和下一个结点的引用。

1 / 4

  • 默认

讲解

实现栈、队列、邻接表,以及需要频繁在已知位置插入删除的场景。

  1. 01每个结点保存 value 和 next(双向链表再加 prev)。
  2. 02头插:new.next = head; head = new。
  3. 03查找必须从 head 线性扫描。
  4. 04反转:用 prev / curr / next 三个指针逐个翻转。

易错点

  • 操作结点前先判空,否则空指针。
  • 修改 next 前先保存后继,否则链表断开。

代码

class Node {
  constructor(val, next = null) { this.val = val; this.next = next; }
}
function reverse(head) {
  let prev = null, curr = head;
  while (curr) {
    const nxt = curr.next;
    curr.next = prev;
    prev = curr; curr = nxt;
  }
  return prev;
}

相关课题