当前位置:首页 > JavaScript

js实现链表思路

2026-04-07 13:19:31JavaScript

实现链表的基本结构

链表由节点(Node)组成,每个节点包含两个部分:

  • value:存储数据
  • next:指向下一个节点的引用(默认为 null
class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

初始化链表

链表类(LinkedList)需维护一个头节点(head)和链表长度(size):

class LinkedList {
  constructor() {
    this.head = null;
    this.size = 0;
  }
}

插入节点

尾部插入
遍历链表找到最后一个节点,将新节点链接到其 next

append(value) {
  const newNode = new Node(value);
  if (!this.head) {
    this.head = newNode;
  } else {
    let current = this.head;
    while (current.next) {
      current = current.next;
    }
    current.next = newNode;
  }
  this.size++;
}

头部插入
新节点的 next 指向原头节点,并更新链表的 head

prepend(value) {
  const newNode = new Node(value);
  newNode.next = this.head;
  this.head = newNode;
  this.size++;
}

删除节点

按值删除
遍历链表找到目标节点的前驱节点,修改其 next 以跳过目标节点:

remove(value) {
  if (!this.head) return;
  if (this.head.value === value) {
    this.head = this.head.next;
    this.size--;
    return;
  }
  let current = this.head;
  while (current.next) {
    if (current.next.value === value) {
      current.next = current.next.next;
      this.size--;
      return;
    }
    current = current.next;
  }
}

查找节点

遍历链表,匹配目标值:

contains(value) {
  let current = this.head;
  while (current) {
    if (current.value === value) {
      return true;
    }
    current = current.next;
  }
  return false;
}

遍历链表

输出所有节点的值:

js实现链表思路

print() {
  let current = this.head;
  const values = [];
  while (current) {
    values.push(current.value);
    current = current.next;
  }
  console.log(values.join(" -> "));
}

示例用法

const list = new LinkedList();
list.append(1);
list.append(2);
list.prepend(0);
list.print(); // 输出: 0 -> 1 -> 2
list.remove(1);
list.print(); // 输出: 0 -> 2
console.log(list.contains(2)); // 输出: true

标签: 思路链表
分享给朋友:

相关文章

vue 多选实现思路

vue 多选实现思路

多选框组件实现 使用Vue内置的v-model指令绑定数组类型数据,当选中多个选项时,会自动将值添加到数组中 <template> <div> <label…

vue实现文件上传思路

vue实现文件上传思路

Vue 文件上传实现思路 使用原生 HTML5 文件上传 通过 <input type="file"> 元素结合 Vue 的数据绑定和事件处理实现基础文件上传功能。 <templa…

vue虚拟列表实现思路

vue虚拟列表实现思路

虚拟列表的核心概念 虚拟列表是一种优化长列表渲染性能的技术,通过仅渲染可视区域内的元素减少DOM节点数量。其核心思想是动态计算可见区域的数据索引,避免全量渲染。 计算可视区域范围 监听滚动事件,根据…

权限管理实现思路vue

权限管理实现思路vue

基于Vue的权限管理实现思路 角色权限模型设计 构建RBAC(基于角色的访问控制)模型,包含用户、角色、权限三层结构。用户关联角色,角色关联权限菜单或操作权限点。权限数据通常包括路由权限和功能权限两种…

js节流防抖实现思路

js节流防抖实现思路

节流(Throttle)的实现思路 节流的核心思想是在一定时间内,无论事件触发多少次,只执行一次回调函数。适用于高频事件(如滚动、鼠标移动)的场景。 function throttle(fn, de…

js实现链表

js实现链表

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。与数组不同,链表在内存中不是连续存储的,插入和删除操作更高效,但访问元素需要遍历。 链表的实现 定义…