单向链表之javascript实现增删改查

一、初始化节点

//初始化节点
class Node {
    constructor(key) {
        this.next = null;
        this.key = key;
    }
}

二、初始化链表及其常用方法

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

    //尾部插入节点
    append(element) {
        let node = new Node(element);
        let current = this.head;
        if (this.head == null) {
            this.head = node;
        } else {
            while (current.next) {
                current = current.next;
            }
            current.next = node;
        }
        this.length++;
    }


    //指定位置插入节点
    insert(element, pos) {
        let node = new Node(element);
        let current = this.head;
        let pre;
        if (pos >= 0 && pos <= this.length) {
            if (pos == 0) {
                this.head = node;
                node.next = current;
            } else {
                let i = 0;
                while (i++ < pos) {
                    pre = current;
                    current = current.next;
                }
                node.next = current;
                pre.next = node;
            }
            this.length++;
        } else {
            return console.log("插入位置无效!");
        }
    }


    //删除指定位置节点
    deleteAt(pos) {
        let current = this.head;
        let pre;
        let index = 0;
        if (pos >= 0 && pos < this.length) {
            if (pos == 0) {
                this.head = current.next;
            } else {
                while (index++ < pos) {
                    pre = current;
                    current = current.next;
                }
                pre.next = current.next;
            }

            this.length--;
            //返回删除的节点数值
            return current.key;

        } else {
            return console.log("删除位置无效!");
        }
    }


    //指定元素的索引
    indexOf(element) {
        let index = 0;
        let current = this.head;
        while (current) {
            if (current.key == element) {
                return index;
            }
            index++;
            current = current.next;
        }
        //搜索不到该数据
        return -1;
    }

    //删除指定数值的节点
    remove(element) {
        let index = this.indexOf(element);
        this.deleteAt(index);
    }
}

三、测试

创建一个新链表,插入数据并进行如下操作:

let list = new LinkedList();
console.log("append", list);

list.append(1); //尾部插入数据
list.append(5);
list.append(2);
list.append(6);
console.log("append", list);

list.insert(11, 3); //指定位置的插入
console.log("insert", list);

list.deleteAt(2);  //删除指定位置数据
console.log("deleteAt", list);

console.log(list.indexOf(11));  //查找索引
发布了67 篇原创文章 · 获赞 4 · 访问量 5955

猜你喜欢

转载自blog.csdn.net/DZY_12/article/details/103577643