// 新建节点
class Node {
constructor(val) {
this.value = val
this.next = null
}
}
// 单向链表
class LinkedList {
constructor(val) {
this.length = 0
this.head = null
}
// 新增节点
append(val) {
let newNode = new Node(val)
if (this.head === null) {
this.head = newNode
} else {
let p = this.head
while (p.next) {
p = p.next
}
p.next = newNode
}
this.length++
}
// 在某位置插入新值
insert(index, val) {
if (index < 0 || index > this.length - 1) {
return false
}
let newInsertNode = new Node(val)
let current = this.head
let currIndex = 0
if (index === 0) {
newInsertNode.next = current
this.head = newInsertNode
} else {
let pre = null
while (currIndex < index) {
pre = current
current = current.next
currIndex++
}
newInsertNode.next = current
pre.next = newInsertNode
}
this.length++
return true;
}
//根据位置删除指定节点,成功返回元素,失败返回null
removeAt(position) {
if (position >= 0 && position < this.length) {
var current = this.head //current指针用来指向该指定节点
var previous = null //previous指针指向current指针前一个节点
var index = 0 //纪录是否到达指定位置
if (position == 0) {
this.head == current.next
} else {
while (index < position) {
previous = current //每次将previous指针和current指针向后移动一个,直到到达指定节点
current = current.next
index++
}
previous.next = current.next //该指定节点的前一个指针越过指定节点,直接指向其下一个节点
}
this.length-- //别忘了更新链表长度
return current.val //返回该元素
} else {
return null
}
}
//根据元素删除指定元素,成功返回已删除的节点,失败返回null
remove(val) {
let index = this.find(val)
return this.removeAt(index)
}
//根据元素查找节点,成功返回给定元素的索引,如果没有则返回-1
find(val) {
var current = this.head
var index = 0
if (current.val == val) {
return 0
}
while (current) {
if (current.val == val) {
return index
}
current = current.next
index++
}
return -1
}
isEmpty() {
return this.length == 0
}
size() {
return this.length
}
toString() {
let str = ''
let current = this.head
while (current) {
str += ',' + current.val
current = current.next
}
return str
}
}
let newList = new LinkedList()
newList.append('1')
newList.append('2')
newList.insert(1, 4)
console.log(JSON.stringify(newList));
原文链接:https://blog.csdn.net/weixin_43221323/article/details/106241314