letLinkedlist = function(){ let head = null let length = 0 //辅助类的添加 letNode = function(element){ this.element = element this.next = null } //链表追加插入 this.append = function(element){ let node = newNode(element) let current = head if(head==null){ head = node }else{ while(current.next){ current = current.next } current.next = node } length++; return head; } //链表在某个位置插入 this.insertNode = function(element,position){ let node = newNode(element) //解决越界问题 if(position>-1 && position<length){ if(position == 0){ let current = head head = node head.next = current }else{ let index = 0 let current = head let previous = null while(index < position){ previous = current current = current.next index++; } previous.next = node node.next = current } length++; return current; }
}
//链表通过位置删除节点 this.removeatNode = function(position){ if(position>-1 && position<length){ let current = head if(position == 0){ head = current.next }else{ let previous = null let index = 0 while(index<position){ previous = current current = current.next index++ } previous.next = current.next; } length--; return current; } returnnull; } //链表获取元素位置 this.indexOf = function(element){ let index =0 let current = head while(current){ if(current.element==element){ return index; } current = current.next index++ } return -1; } //链表删除元素 this.removeNode = function(element){