js单链表的封装
class Node {
constructor(element) {
this.element = element
this.next = null
}
}
class LinkedList {
constructor() {
this.count = 0
this.head = null
}
push(element) {
const node = new Node(element)
if (this.head === null) {
this.head = node
} else {
let current = this.head
while (current.next !== null) {
current = current.next
}
current.next = node
}
this.count++
}
//指定位置删除
removeAt(index) {
if (index >= 0 && index < this.count) {
let current = this.head
if (index === 0) {
this.head = this.head.next
} else {
let previous = this.getNodeAt(index - 1)
current = this.getNodeAt(index)
previous.next = current.next
}
this.count--
return current.element
}
return
}
//获取指定下标的节点
getNodeAt(index) {
if (index >= 0 && index < this.count) {
let node = this.head
for (let i = 0; i < index; i++) {
node = node.next
}
return node
}
return
}
equalFn(a, b) {
return JSON.stringify(a) === JSON.stringify(b)
}
indexOf(element) {
let current = this.head
for (let i = 0; i < this.count; i++) {
if (this.equalFn(element, current.element)) {
return i
}
current = current.next
}
return -1
}
//删除指定元素
remove(element) {
const index = this.indexOf(element)
return this.removeAt(index)
}
insert(element, index) {
if (index >= 0 && index <= this.count) {
const node = new Node(element)
if (index === 0) {
let current = this.head
node.next = current
this.head = node
} else {
let previous = this.getNodeAt(index - 1)
let current = previous.next
node.next = current
previous.next = node
}
this.count++
return true
}
return false
}
isEmpty() {
return this.size() === 0
}
size() {
return this.count
}
getHead() {
return this.head
}
}
let link = new LinkedList()