当前位置:首页 > JavaScript

js实现链表

2026-04-05 13:43:03JavaScript

实现链表的基本结构

在JavaScript中,链表可以通过对象和引用来实现。每个节点包含一个值(value)和一个指向下一个节点的指针(next)。

class ListNode {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

创建链表类

链表类通常包含头节点(head)和一些基本操作方法,如插入、删除和遍历。

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

插入节点

插入节点分为头部插入和尾部插入两种常见方式。

头部插入
新节点成为链表的头节点,原头节点成为新节点的下一个节点。

js实现链表

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

尾部插入
遍历链表找到最后一个节点,将新节点添加到末尾。

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

删除节点

删除指定值的节点需要遍历链表,找到目标节点并调整指针。

js实现链表

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

遍历链表

遍历链表可以通过循环访问每个节点的next指针,直到nextnull

traverse() {
  let current = this.head;
  while (current) {
    console.log(current.value);
    current = current.next;
  }
}

查找节点

查找链表中是否存在某个值,返回布尔值或节点。

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

反转链表

反转链表需要调整每个节点的next指针方向。

reverse() {
  let prev = null;
  let current = this.head;
  while (current) {
    const next = current.next;
    current.next = prev;
    prev = current;
    current = next;
  }
  this.head = prev;
}

示例用法

const list = new LinkedList();
list.insertAtTail(1);
list.insertAtTail(2);
list.insertAtTail(3);
list.traverse(); // 输出: 1 2 3
list.reverse();
list.traverse(); // 输出: 3 2 1
list.deleteNode(2);
list.traverse(); // 输出: 3 1

以上代码实现了链表的基本功能,包括插入、删除、遍历和反转。链表在JavaScript中常用于实现队列、栈或其他需要动态大小的数据结构。

标签: 链表js
分享给朋友:

相关文章

jquery.js

jquery.js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,用于简化 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它的设计宗旨是“Write Less, Do Mor…

css3结合js制作

css3结合js制作

CSS3 结合 JavaScript 制作动态效果 CSS3 和 JavaScript 结合可以实现丰富的动态效果,包括动画、交互和响应式设计。以下是几种常见的实现方式: CSS3 动画与 Java…

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callback) {…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…