letLinkedList = function(){ let head = null let length = 0 //定义一个辅助节点类 letNode = function(element){ this.previous = null this.element = element this.next = null } //在链表后面追加 this.append = function(element){ let node = newNode(element) let current = head if(length == 0){ head = node }else{ while(current.next){ current = current.next } node.previous = current current.next = node
} length++ return head; } //链表在某个地方插入 this.insertNode = function(element,position){ let node = newNode(element) let current = head if(position>=0&&position<length){ if(position==0){ head = node current.previous = head head.next = current }else{ let last = null let index = 0 while(index<position){ last = current current = current.next index++; } //设置好新节点的previous和next node.previous = last node.next = current //分别设置之前前节点的下一个目标为node,后节点的上一个目标为node current.previous = node last.next = node } length++; return current; } returnnull; }
//链表在某个位置删除元素 this.removeatNode = function(position){ let current = head if(position>=0&&position<length){ if(position==0){ head = current.next; if(head){ head.previous = null; } }else{ let index = 0 let last = null while(index<position){ last = current current = current.next index++; } last.next = current.next if(current.next){ current.next.previous = last } } 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; }