javascript数据结构-单链表

84 阅读1分钟

1、首先创建一个Node节点类

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

2、创建一个LinkedList

主要实现了对单链表的增删查功能:

class LinkedList {
    constructor() {
        this.count = 0;
        this.head = null;
    }
    
    // 插入元素到链表末尾
    push(value) {
        const node = new Node(value);
        if (!this.head) {
            this.head = node;
        } else {
            let current;
            current = this.head;
            while(current.next) {
                current = current.next;
            }
            current.next = node;
        }
        this.count++;
    }

    // 插入元素
    insert(value, index) {
        const node = new Node(value);
        if (index === 0) {
            let current = this.head;;
            node.next = current;
            this.head = node;
            this.count++;
        } else if (index >= this.count){
            this.push(value);
        } else {
            let previous = this.get(index - 1);
            let current = previous.next;
            node.next = current;
            previous.next = node;
            this.count++;
        }
    }

    // 获取元素节点
    get(index) {
        let current = this.head;
        for (let i = 0; i < index && current.next; i++) {
            current = current.next;
        }
        return current;;
    }
    
    // 根据索引删除元素
    removeAt(index) {
        // 移除头节点
        if (index === 0) {
            this.head = this.head.next;
        } else {
            let previous = this.get(index - 1);
            console.log(previous);
            let current = previous.next;
            console.log(current);
            previous.next = current.next;
        }
        this.count--;
    }

    size() {
        return this.count;
    }

    indexOf(value) {
        let current = this.head;
        for (let i = 0; i < this.count; i++) {
            // 如果值相等则返回对应位置索引
            if (current.value === value) {
                return i;
            }
            current = current.next;
        }
        return -1;
    }

    remove(value) {
        let current = this.head;
        for (let i = 0; i < this.count; i++) {
            if (current.value === value) {
                this.removeAt(i);
            }
            current = current.next;
        }
        return -1;
    }
}