当前位置:首页 > JavaScript

js实现链表思路

2026-02-02 19:34:45JavaScript

实现链表的基本结构

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

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

初始化链表

创建链表类,初始化头节点(head)和长度(size):

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

插入节点

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

js实现链表思路

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指向原头节点,并更新头节点为新节点:

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

删除节点

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

js实现链表思路

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;
}

遍历链表

输出所有节点的值:

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

注意事项

  • 插入/删除时需处理边界条件(如空链表或头节点操作)。
  • 双向链表需额外维护prev指针,循环链表需将尾节点的next指向头节点。

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

相关文章

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…

vue实现登录思路

vue实现登录思路

Vue 登录功能实现思路 1. 前端页面设计 使用 Vue 的单文件组件(SFC)构建登录页面,包含表单元素(用户名、密码输入框)和提交按钮。表单需绑定 v-model 实现双向数据绑定,并通过 v-…

vue tree 实现思路

vue tree 实现思路

Vue Tree 组件实现思路 数据结构设计 树形组件的数据通常采用嵌套结构,每个节点包含 label、children 等属性。例如: const treeData = [ { lab…

vue 多选实现思路

vue 多选实现思路

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

vue实现mvvm思路

vue实现mvvm思路

Vue 实现 MVVM 的思路 Vue 的 MVVM(Model-View-ViewModel)实现主要依赖于数据绑定和响应式系统。以下是其核心实现思路: 数据劫持与响应式 Vue 使用 Obje…

vue实现动态时钟思路

vue实现动态时钟思路

实现动态时钟的思路 使用Vue实现动态时钟的核心在于实时更新显示的时间,并通过数据绑定自动渲染到页面上。以下是具体实现方法: 使用Date对象获取当前时间 通过JavaScript的Date对象可以…