js算法练习--链表
class Node{ constructor(element){ this.element=element; this.next=null; } } class Linked{ constructor(){ this.head=null; this.length=0; } append(element){ let node=new Node(element); if(this.head==null) this.head=node; else{ let current=this.head; while(current && current.next){ current=current.next; } current.next=node; } this.length++; } Insert(element,position){ if(position<0 || position>this.length) return false; let node=new Node(element); let previous=null; let index=0; let current=this.head; for(index;index<=position;index++){ if(index==0 && index==position && current==null){ this.head=node; } else{ previous=current; current=current.next; } } if(index>0){ node.next=current; previous.next=node; } this.length++; return true; } RemoveAt(position){ if(position<0 || position>this.length) return false; if(position==0){ if(this.head && this.head.next){ this.head=this.head.next; } else{ this.head=null; } } else{ let current=this.head; let previous=null; let index=0; while(index++<position){ previous=current; if(current.next) current=current.next; } if(position==this.length) { previous.next=null; } else{ previous.next=current.next; } } this.length--; return true; } FindElement(element){ var index=-1; var current=this.head; while(current){ if(current.element===element){ return index+1; } current=current.next; index++; } return -1; } IsEmpty(){ return this.length==0; } Size(){ return this.length; } Remove(element){ var index=this.FindElement(element); if(index==-1) return false; else return this.RemoveAt(index); } ToString(){ debugger; let data=[]; let current=this.head; while(current){ data.push(current.element); current=current.next; } return data.toString(); } } let link=new Linked(); link.append(1);