function listNode(val){ //创建节点 this.val=val? val:null this.next=null } class Node{ constructor() { this.length=0 //链表长度 this.head=null //头节点 } getNode(index){ //用于获取相应索引的节点 if(index<0||index>this.length) throw new Error('out range') let p=this.head for(let i=0;i<index;i++) p=p.next return p } append(element){ //在链表中向尾部添加节点 var node=new listNode(element) if(this.head==null) this.head=node else{ let current=this.getNode(this.length-1) //拿到尾部节点 current.next=node } this.length++ } appendAt(element,n){ //在指定位置添加节点 if(n<0||n>this.length){ throw new Error('out range ') } let node=new listNode(element) if(n==0) { node.next=this.head //将原链表连接到新建节点后边 this.head=node //使新节点成为头节点 }else { let nn = this.getNode(n - 1) //拿到添加位置节点的上一个节点 node.next = nn.next nn.next = node } this.length++ } removeAt(n){ if(n==0) { this.head=this.head.next }else{ let nn=this.getNode(n-1) //拿到要删除节点的上一个节点 nn.next=nn.next.next} this.length-- } indexOf(element){ let node=this.head for (let n=0;n<this.length;n++){ if(element==node.val) return n else{ node=node.next } } return -1 } } var a=new Node() a.append(1) a.append(2) console.log(a) a.appendAt(3,0) console.log(a) 注意!在需要对链表进行查找等操作时,不能直接利用头节点,需要创建一个新节点来代表头节点。
constucter 用来保存类中的属性(不知道对不对,不确定。。。。)