双向链表

双向链表结构:

img

先在Html引入js文件:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script src="./04_双向链表.js"></script>
</head>
<body>
</body>
</html>

双向链表.js

let LinkedList = function(){
let head = null
let length = 0
//定义一个辅助节点类
let Node = function(element){
this.previous = null
this.element = element
this.next = null
}
//在链表后面追加
this.append = function(element){
let node = new Node(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 = new Node(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;
}
return null;
}

//链表在某个位置删除元素
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;
}
return null;
}

//链表获取元素位置
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){
return this.removeatNode(this.indexOf(element))
}

//检查是否为空栈
this.isEmpty = function(){
return length == 0
}

//查询链表长度
this.size = function(){
return length
}

//获取链表
this.getHead = function(){
return head;
}


}

let l = new LinkedList();