js实现简单的单链表 (初次接触,小白)
/* 定义一个节点类 */
class Node {
constructor(element) {
//元素本身
this.element = element
//指向位置
this.next = null
}
}
/* 定义列表 */
class MyList {
constructor() {
//列表的长度
this.size = 0
// 列表的头指针指向
this.head = null
}
//向列表中添加元素
append(element) {
// 列表长度为0, 默认添加到头部
if(this.head === null){
this.head = new Node(element)
}else{
//获取列表的最后一个元素
let lastElement = this.getNode(this.size -1)
//最后一个元素的next 指向当前的元素
lastElement.next = new Node(element)
}
//列表的长度自增
this.size ++
}
/* 根据位置 索引 删除指定的元素 */
remove(postion) {
//position 越界判断
if(postion < 0 || this.postion > this.size) {
throw Error('out of position')
}
if(postion === 0) {
// 删除列表的第一个元素
this.head = this.head.next
} else {
//获取当前索引的上一个元素
const preNode = this.getNode(postion - 1)
//获取当前索引的元素
const curNode = this.getNode(postion)
//上一个节点的 next 指向 当前节点的 next
preNode.next = curNode.next
}
// 列表的长度减一
this.size --
}
/* 向列表中插入元素 position 插入的位置 element插入的元素 */
insert(postion, element) {
// 插入索引越界处理
if(postion < 0 || this.postion > this.size) {
throw Error('out of position')
}
// new 出来当前的节点
let current = new Node(element)
//position === 0 向列表的头部插入
if(postion === 0) {
current.next = this.head
this.head = current
}else {
//获取当前位置的上一个节点
let preNode = this.getNode(postion - 1)
current.next = preNode.next
preNode.next = current
}
this.size ++
}
/* 根据index 获取列表的节点 */
getNode(index) {
if(index < 0 || index >= this.size) {
throw Error('index out range')
}
let current = this.head
for(let i = 0; i < index; i++) {
current = current.next
}
return current
}
}
const ll = new MyList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(4)
ll.remove(2)
console.dir(ll,{
depth: 4
});