单向链表

什么是链表:

image-20200429184949517

实现思路框架:

image-20200429185043345

链表具体操作:

image-20200429185137374

image-20200429185218427

先在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="./03_链表.js"></script>
</head>
<body>
</body>
</html>

链表操作.js:

let Linkedlist = function(){
let head = null
let length = 0
//辅助类的添加
let Node = function(element){
this.element = element
this.next = null
}
//链表追加插入
this.append = function(element){
let node = new Node(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 = new Node(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;
}
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))

//具体逻辑如下
// let index = 0
// let current = head
// let previous = null
// let iffind = false
// while(index < length){
// if(current.element == element){
// iffind = true;
// break;
// }
// previous = current
// current = current.next
// index++
// }
// if(index == 0){
// head = current.next;
// length--;
// return head;
// }else if(iffind){
// previous.next = current.next
// length--;
// return head
// }else{
// return null;
// }

}

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

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

//查询整条链表
this.getHead = function(){
return head;
}
}

let l = new Linkedlist()