# 单向链表
// 链表
class Link {
constructor() {
this.length = 0; //链表的长度
this.head = null; //链表的指针
}
// 节点实例
_node(data) {
function node(data) {
this.data = data
this.next = null
}
return new node(data)
}
// 追加节点
append(data) {
const newNode = this._node(data)
if (this.length === 0) {
// 判断添加的是不是第一个节点,如果是第一个节点,就直接添加
this.head = newNode;
} else {
// 不是第一个先找到最后一个然后在往后追加
let curr = this.head;
while (curr.next) {
curr = curr.next
}
curr.next = newNode
}
this.length++;
}
// 在某一位置插入
insert(position, data) {
// 如果是插入第一个和最后一个,交给append处理
const newNode = this._node(data)
if (position > this.length) return false
if (position == 0 || position == this.length) {
this.append(data)
} else {
// 在中间插入,先找到前一个node 改变指向
let index = 0; //遍历使用
let curr = this.head //当前指针
let previous = null;
while (index++ < position) {
// 循环找到要插入的节点位置
previous = curr;
curr = curr.next;
}
// 改变节点的指向
previous.next = newNode;
newNode.next = curr;
}
this.length++;
return true
}
// 获得对应位置上的数据 传一个参数是获取,传两个参数是替换
get(position, data) {
if (this.length == 0 || position > this.length) return false
let index = 0;
let curr = this.head
while (index++ != position) {
curr = curr.next
}
if (data) {
curr.data = data
return true
}
return curr.data
}
// 获得对应数据的下标
indexOf(data) {
if (!data) return false;
let index = 0;
let curr = this.head;
while (index++ < this.length) {
if (curr.data == data) {
return index - 1;
}
curr = curr.next;
}
}
// 删除对应下标的元素
remove(position) {
if (this.length == 0 || position > this.length) return false
let index = 0;
let curr = this.head
let previous = null;
while (index++ != position) {
previous = curr
curr = curr.next
}
previous.next = curr.next
this.length--;
return true
}
}
const link = new Link()
link.append('11')
link.append('12')
console.log(link.remove(1))
console.log(link)
# 双向链表
# 总结
链表的写的效率比较高,读的效率低,可以存储不连续的数据