//链表结构
//封装节点
class Node {
constructor (data) {
this.data = data
this.next = null
}
}
class LinkList {
constructor () {
//初始化,空链表,长度为0
this.head = null
this.length = 0
}
//追加数据
append (data) {
// 创建新节点
let node = new Node(data)
// 当前为空链表
if (!this.head) {
// 让head指向新节点
this.head = node
}else {
// 找到尾节点
let current = this.head
while (current.next) {
current = current.next
}
current.next = node
}
this.length++
}
// 插入数据
insert (posi, data) {
// 判断position是否合法
if (posi < 0 || posi > this.length) return false
let node = new Node(data)
if (posi == 0) {
node.next = this.head
this.head = node
}else {
let current = this.head
let index = 0
while (index++ < posi - 1) {
current = current.next
}
node.next = current.next
current.next = node
}
this.length++
return true
}
// 查找数据
indexOf (data) {
let current = this.head
let index = 0
while (current) {
if (current.data === data) {
return index
}
index++
current = current.next
}
return -1
}
// 移除指定位置数据
removeAt (posi) {
// Number.isInteger()判断是否为整数
if (posi < 0 || posi > this.length -1) return false
if (posi == 0) {
this.head = this.head.next
}else {
let current = this.head
let index = 0
while (index++ < posi - 1) {
current = current.next
}
current.next = current.next.next
}
this.length--
return true
}
remove (data) {
//删除所有data的数据
while (this.indexOf(data) != -1) {
//删除第一个出现的data数据
this.removeAt(this.indexOf(data))
}
return true
}
isEmpty () {
return this.head == null
}
size () {
return this.length
}
}
var list = new LinkList()
list.append(1)
list.append(2)
list.append(3)
list.insert(0, 0)
list.insert(4, 4)
list.insert(0, 'b')
list.insert(3, 'b')
list.insert(5, 'b')
console.log(list)
console.log(list.indexOf('b'))
list.remove('b')