当前位置:首页 > 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

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指向:

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

注意事项

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

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

相关文章

h5翻牌游戏实现思路

h5翻牌游戏实现思路

翻牌游戏实现思路 游戏核心逻辑 翻牌游戏(Memory Game)的核心是通过匹配成对的卡片来消除它们。玩家每次翻开两张牌,若相同则消除,否则翻回背面。游戏目标是在最短时间内或最少步数内消除所有牌。…

vue列表多选实现思路

vue列表多选实现思路

Vue列表多选实现思路 基础实现:v-model绑定数组 通过v-model绑定一个数组,配合checkbox的value属性实现多选。选中时自动将值添加到数组,取消选中时从数组中移除。 &…

vue轮播抽奖实现思路

vue轮播抽奖实现思路

Vue轮播抽奖实现思路 轮播抽奖是一种常见的互动效果,通过快速切换选项最终停在某个奖品上。以下是基于Vue的实现思路和关键步骤: 核心逻辑设计 使用Vue的data管理当前高亮项的索引和抽奖状态…

vue实现轮播图思路

vue实现轮播图思路

实现轮播图的核心思路 在Vue中实现轮播图通常需要结合组件化、动态数据绑定和动画过渡。核心思路包括数据驱动渲染、自动轮播逻辑、用户交互控制以及无缝循环效果。 数据准备与结构设计 定义轮播图数据数组,…

php链表实现

php链表实现

PHP 链表实现 链表是一种线性数据结构,由节点组成,每个节点包含数据和指向下一个节点的指针。在 PHP 中,可以通过类来实现链表。 链表节点类 链表的基本单位是节点,通常包含数据(data)和指向…

js中如何实现单链表

js中如何实现单链表

单链表的基本概念 单链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。链表的头节点是访问整个链表的起点,尾节点的指针通常指向null。 单链表的节点定义 在JavaS…