Published
Edited
Sep 9, 2021
Insert cell
# JS链表表述
Insert cell
## 单向链表
Insert cell
### 测试数据
Insert cell
arr = [1,2,3,4,5];
Insert cell
### 链表节点描述
Insert cell
class Node{
constructor(value){
this.value = value;
this.next = null;
}
}

Insert cell
### 链表Chain
Insert cell
class Chain{
constructor(){
this.head = new Node(0);
}

insert(pointValue,newNode){
const current = this.find(pointValue);
newNode.next = current.next;
current.next = newNode;
}

find(value){
let current = this.head;
while(current.value !== value && current.next){
current = current.next;
}
return current;
}

findPrevious(value){
let current = this.head;
while(current.next !== null && current.next.value !== value){
current = current.next;
}
return current;
}

findLast(){
let current = this.head;
while(current.next !== null){
current = current.next;
}
return current;
}

remove(value){
const pre = this.findPrevious(value);
if(pre.next !== null){
pre.next = pre.next.next;
}
}

}
Insert cell
### 数组转换成链表
Insert cell
function genChain(arr){
const chain = new Chain();
for(let i=1,len=arr.length;i<len;i++){
chain.insert(i-1,new Node(i));
}
return chain;
}
Insert cell
genChain(arr);
Insert cell
## 双向链表
Insert cell
class DoubleNode{
constructor(v){
this.value = v;
this.next = null;
this.pre = null;
}
}
Insert cell
class DoubleChain{
constructor(){
this.head = new DoubleNode(0);
}

insert(pointValue,newNode){
const current = this.find(pointValue);
newNode.next = current.next;
newNode.pre = current;
current.next = newNode;
}

find(value){
let current = this.head;
while(current.value !== value && current.next){
current = current.next;
}
return current;
}

// findPrevious(value){
// let current = this.head;
// while(current.next !== null && current.next.value !== value){
// current = current.next;
// }
// return current;
// }

findLast(){
let current = this.head;
while(current.next !== null){
current = current.next;
}
return current;
}

remove(value){
const node = this.find(value);
if(node.next !== null){
node.pre.next = node.next;
node.next.pre = node.pre;
node.next = null;
node.pre = null;
}
}

}
Insert cell
## 循环列表
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more