首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

js实现单向链表

单向链表是一种线性数据结构,其中每个元素都包含一个指向下一个元素的指针。在JavaScript中,可以通过定义节点类和链表类来实现单向链表。以下是实现单向链表的基础概念、优势、类型、应用场景以及相关代码示例:

基础概念

  1. 节点(Node):链表的基本单元,包含数据和指向下一个节点的指针。
  2. 链表(LinkedList):由一系列节点组成的数据结构,每个节点通过指针连接。

优势

  • 动态大小:链表的大小可以动态增长或缩小。
  • 插入和删除效率高:在已知位置的情况下,插入和删除操作的时间复杂度为O(1)。
  • 内存利用率高:不需要连续的内存空间。

类型

  • 单向链表:每个节点只有一个指向下一个节点的指针。
  • 双向链表:每个节点有两个指针,分别指向前一个节点和后一个节点。

应用场景

  • 实现其他数据结构:如栈、队列、符号表等。
  • 需要频繁插入和删除操作的场景

代码示例

以下是JavaScript实现单向链表的示例代码:

代码语言:txt
复制
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

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

    // 在链表末尾添加节点
    append(data) {
        const node = new Node(data);
        if (this.head === null) {
            this.head = node;
        } else {
            let current = this.head;
            while (current.next !== null) {
                current = current.next;
            }
            current.next = node;
        }
        this.size++;
    }

    // 在指定位置插入节点
    insertAt(data, index) {
        if (index < 0 || index > this.size) {
            return console.log("Index out of bounds");
        }
        const node = new Node(data);
        if (index === 0) {
            node.next = this.head;
            this.head = node;
        } else {
            let current = this.head;
            let previous;
            let count = 0;
            while (count < index) {
                previous = current;
                current = current.next;
                count++;
            }
            node.next = current;
            previous.next = node;
        }
        this.size++;
    }

    // 删除指定位置的节点
    removeAt(index) {
        if (index < 0 || index >= this.size) {
            return console.log("Index out of bounds");
        }
        let current = this.head;
        if (index === 0) {
            this.head = current.next;
        } else {
            let previous;
            let count = 0;
            while (count < index) {
                previous = current;
                current = current.next;
                count++;
            }
            previous.next = current.next;
        }
        this.size--;
        return current.data;
    }

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

// 示例用法
const list = new LinkedList();
list.append(10);
list.append(20);
list.append(30);
list.insertAt(15, 1);
list.printList(); // 输出: 10 15 20 30
list.removeAt(2);
list.printList(); // 输出: 10 15 30

可能遇到的问题及解决方法

  1. 空链表操作:在操作前检查链表是否为空。
  2. 索引越界:在插入和删除操作前检查索引是否在有效范围内。
  3. 内存泄漏:确保删除节点时正确更新指针,避免内存泄漏。

通过上述代码示例和解释,你可以更好地理解单向链表的实现及其应用。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券