class List {
constructor(headValue) {
this.head = headValue ? this.createNode(headValue) : null
this.length = headValue ? 1 : 0
}
createNode(value) {
return {
value,
next: null
}
}
add(value) {
let current = this.head
while(current.next) {
current = current.next
}
current.next = this.createNode(value)
this.length = this.length + 1
}
exist(value) {
let current = this.head
let index = 1
while(current) {
if (current.value === value) return index
index ++
current = current.next
}
return false
}
findByIndex(index) {
if (index === 1) return this.head
if (index > this.length) return null
let current = this.head
while (index > 1) {
current = current.next
index--
}
return current
}
delByIndex(index) {
if (this.head === null || index < 1 || index > this.length) return null
this.length = this.length - 1
if (index === 1) {
this.head = this.head.next
return true
}
const pre = this.findByIndex(index - 1)
pre.next = pre.next.next
return true
}
delByValue(value) {
const index = this.exist(value)
if (index === false) return index
return this.delByIndex(index)
}
insert(index, value) {
if (index === 0) {
const newNode = this.createNode(value)
newNode.next = this.head
this.head = newNode
this.length = this.length + 1
return true
}
if (index > this.length) return false
const now = this.findByIndex(index)
const node = this.createNode(value)
node.next = now.next
now.next = node
this.length++
return
}
reverseList() {
if (this.head === null || this.head.next === null) return this.head
let res = null
let next;
let current = this.head
while (current) {
next = current.next
current.next = res
res = current
current = next
}
return res
}
isCircle() {
if (this.length < 2) return false
let fast = this.head
let slow = this.head
while(fast && fast.next) {
fast = fast.next.next
slow = slow.next
if (fast === slow) return true
}
return false
}
back(index) {
if (index === this.length) return this.head
if (index < 1 || index > this.length) return null
let fast = this.head
let slow = this.head
while(index--) {
fast = fast.next
}
while(fast) {
fast = fast.next
slow = slow.next
}
return slow
}
}