单向链表之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));  //查找索引

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值