链表是一种常用的数据结构,它由一系列节点组成,每个节点包含一个数据元素和指向下一个节点的指针。链表的插入操作是将新节点插入到链表的特定位置,常见的插入方式有在链表头部插入和在链表尾部插入。

下面是用 Node.js 实现链表插入的函数:

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

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

  // 在链表头部插入新节点
  insertAtHead(data) {
    const newNode = new Node(data);
    newNode.next = this.head;
    this.head = newNode;
    this.size++;
  }

  // 在链表尾部插入新节点
  insertAtTail(data) {
    const newNode = new Node(data);
    if (this.head === null) {
      this.head = newNode;
    } else {
      let current = this.head;
      while (current.next !== null) {
        current = current.next;
      }
      current.next = newNode;
    }
    this.size++;
  }

  // 在指定位置插入新节点
  insertAtPosition(data, position) {
    if (position < 0 || position > this.size) {
      console.log('Invalid position');
      return;
    }
    const newNode = new Node(data);
    if (position === 0) {
      newNode.next = this.head;
      this.head = newNode;
    } else {
      let current = this.head,
        prev = null,
        index = 0;
      while (index < position) {
        prev = current;
        current = current.next;
        index++;
      }
      prev.next = newNode;
      newNode.next = current;
    }
    this.size++;
  }

  // 打印链表
  printList() {
    let current = this.head,
      list = '';
    while (current !== null) {
      list += current.data + ' ';
      current = current.next;
    }
    console.log(list);
  }
}

// 测试代码
const ll = new LinkedList();
ll.insertAtHead(1);
ll.insertAtHead(2);
ll.insertAtTail(3);
ll.insertAtTail(4);
ll.insertAtPosition(5, 2);
ll.printList(); // 输出:2 1 5 3 4

上述代码定义了一个Node节点类和一个LinkedList链表类,其中insertAtHead()方法用于在链表头部插入新节点,insertAtTail()方法用于在链表尾部插入新节点,insertAtPosition()方法用于在指定位置插入新节点,printList()方法用于打印链表。我们可以根据需要选择适当的方法进行链表插入操作。

Node.js 链表插入函数实现详解

原文地址: https://www.cveoy.top/t/topic/oCIe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录