声明元素及链表
function Node(element){
this.element = element;//值
this.next = null;//尾部
this.prev = null;//头部
}
function DoublyLinkedList(){
let length = 0;
let head = null;//连接前一项
let tail = null;//连接后一项
//方法
this.append = append; //向链表尾部添加元素
this.insert = insert; //向链表特定位置插入元素
}
向链表尾部添加元素
function append(element){
let node = new Node(element);
let current;
if(this.head == null){ //为空链表时,把head和tail都指向这个新节点
this.head = node;
this.tail = node;
}else{
current = this.tail; //获取最后一项
current.next = node; //在最后一项后添加
node.prev = current; //连接头部
this.tail = node; //更新最后一个节点
}
length++;
}
向链表特定位置插入元素
function insert(position, element){
if(position < 0 || position > length){//检查越界值
return false;
}
let node = new Node(element);
let current = this.head;
let index = 0;
let previous;
if(position == 0){ //在第一个位置添加
if(!this.head){ //空列表情况
this.head = node;
this.tail = node;
}else{
node.next = current;
current.prev = node;
this.head = node;
}
}else if(position == length){//添加到尾部时
current = this.tail;
current.next = node;
node.prev = current;
this.tail = node;
}else{
while(index++ < position){
previous = current;
current = current.next;//找出要插入的位置
}
node.next = current;
current.prev = node;
previous.next = node;
node.prev = previous;
}
length++;
return true;
}
验证代码同上一篇