javascript实现单链表

首先定义节点类:

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

然后定义单链表类LinkList,涉及到的主要方法有追加、插入、删除。其中插入涉及到从表头,中间,尾部插入。删除也涉及到是表头删除还是其他位置删除。

//链表
class LinkList{
    constructor(){
        this.head = null;
        this.length = 0;
    }

    //追加元素
    append = (value)=>{
        const node = new Node(value);
        let current = null;
        if(!this.head){
            this.head = node;
        }else{
            current = this.head;
            while(current.next){
                current = current.next;
            }
            current.next = node;
        }
        this.length++ ;
    }

    //根据下标寻找元素
    findValueByIndex = (index)=>{
        if(index<0 || index+1>this.length){
            throw new Error('not a invalid index range');
        }
        if(this.length==0){
            return this.head.data;
        }else{
            let current = this.head;
            let nowIndex = 0;
            while(nowIndex{
        let nowIndex = 0;
        let current = this.head;
        while(nowIndex{
        let current = this.head;
        let newNode = new Node(value);
        let nowIndex = 0;
        while(nowIndex{
        if(index<0 || index>this.length){
            throw new Error('invalid range of this linkList')
        }
        let current = this.head;
        let nowIndex = 0;
        const newNode = new Node(value);
        //头部插入
        if(index===0){
            newNode.next = this.head;
            this.head = newNode;
            this.length++;
            return false;
        }

        let prev = this.head;
        //中间插入
        while(++nowIndex{
        let current = this.head;
        let arr = [];
        let nowIndex = 0;
        while(nowIndex{
        let nowIndex = 0;
        let _this = this;
        return {
            next(){
                if(nowIndex<_this.length){
                    return {
                        done:false,
                        value:_this.findValueByIndex(nowIndex++)
                    }
                }else{
                    return {
                        done:true,
                        value:undefined
                    }
                }
            }
        }
    }
}

测试用例:

let link = new LinkList();
link.append('9');
link.append('8');
link.append('7');
link.append('6');
link.append('5');
link.append('4');
link.append('3');
// link.insertByValue('5','8')
//link.insertByIndex(1,'88')
// console.log(link.deleteByValue('9'))
console.log(link.deleteByIndex(100));
console.log(link.toArray(),link.length,link);
for(let value of link){
    console.log(value,'forof')
}
//console.log(link,'link')

 

你可能感兴趣的:(数据结构,单链表,数据结构,javascript单链表)