链表
加粗样式概念:
链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。
逻辑如下图:
实现代码如下:
class ArrayLink{
constructor(){
this.top = null;
this.length = 0;
}
getValueForIndex(index){
if(index<0 || index> this.length) return null;
let cur = this.top
for(let i = 0; i< index; i++){
cur = cur.next
}
return cur
}
getValueForNode(value){
let cur = this.top
for(let i = 0; i< this.length; i++){
if(cur.value === value) return cur;
cur = cur.next
}
return cur
}
push(value){
let newNode = new Node(value)
let pre = this.top;
if(this.length === 0){
this.top = newNode;
this.length++;
return;
}else{
pre = this.getValueForIndex(this.length-1)
}
pre.next = newNode;
this.length++;
}
insert(index, value){
if(index<0 || index> this.length) return null;
let newNode = new Node(value)
const pre = this.getValueForIndex(index-1)
newNode.next = pre.next;
pre.next = newNode;
this.length++;
}
remove(value){
let cur = this.top;
for(let i = 0; i< this.length-1; i++){
if(cur.next.value === value){
cur.next = cur.next.next;
this.length--;
}
cur = cur.next
}
}
removeAt(index){
const pre= this.getValueForIndex(index-1)
pre.next = pre.next.next;
this.length--;
}
forEach(){
let cur = this.top;
for(let i = 0; i< this.length; i++){
console.log(cur.value);
cur = cur.next
}
}
}
// 节点
class Node{
constructor(value){
this.value = value;
this.next = null;
}
}