链结构类似数组,经过前几天对数组部分方法的重构,大概明白数组中如果想要在中间插入数据的代价是非常大的,需要将后边的所有数据后移。
而链式结构不同,要在链式结构中插入数据就非常简单,只需要将数据指针更改即可,如果说数组类似排队,链式结构更像火车。
class lian {
constructor(value) {
//添加this.next 是为了指向下一个元素
this.next = undefined
//this.text是为了保存自己的值
this.text = value
}
//在链后添加
push(value) {
if (this.next == undefined) {
this.next = new lian(value)
} else {
this.next.push(value)
}
}
//输出
toString() {
let next = this.next
let string = ''
while (next != undefined) {
string += ` ${next.text},`
next = next.next
}
return string
}
//删除
deletes(value) {
let next = this.next
if (next.text == value) {
if (next.next != undefined) {
this.next = next.next
return value
}
this.next = undefined
}
next.deletes(value)
}
// 从任意位置添加
add(value, num, m) {
m = m == undefined ? 0 : m
let next = this.next
if (next != undefined) {
if (m == num) {
let last_next = this.next
this.next = new lian(value)
this.next.next = last_next
return 'ok'
}
m++
next.add(value, num, m)
}
}
//删除最后一个
delete_last(){
let next = this.next
if(next.next==undefined){
let value = next.text
this.next = undefined
return value
}
next.next.delete_last()
}
}
let o = new lian //新建一个链
o.push(1) // 添加1234
o.push(2)
o.push(3)
o.push(4)
o.add(3, 0) //在最前面添加一个3
o.delete_last() //删除最后一个
console.log(o.toString())
这是我对链的理解,如果有什么偏差,请指正,谢谢各位大佬。