- 前端常用的数据结构就是数组 因为前端的数组封装了很多方法:增删改查 以及各种循环操作,但是数组的添加,删除在改变索引的情况下效率不高,数组是一块连续的内存空间,如果数据超过初始定义的长度再往里添加数据的话要扩容效率不高,数组的优势在于可以根据索引查找数据效率很快(所以在查找方面前端可以用对象的方式去查找,和数组索引一样,obj[key] )。
- 链表是一种非连续非顺序的存储结构:每一项包括两部分,当前项的值,以及指向下一个项的指针,链表对于插入删除操作效率比数组高
实现方式
class ListSelf {
head = null
length = 0
CreactNode = class {
constructor(data = '', next = null) {
this.data = data
this.next = next
}
}
append(data) {
const newNode = new this.CreactNode(data)
if (this.length === 0) this.head = newNode
else {
let current = this.head
while (current.next) current = current.next
current.next = newNode
}
return this.length += 1
}
insert(data, insertIndex) {
if (insertIndex < 0 || insertIndex > this.length) return false
const newNode = new this.CreactNode(data)
this.length += 1
if (insertIndex === 0) {
newNode.next = this.head
this.head = newNode
return true
}
let current = this.head,
preItem = null,
index = 0;
while (index++ < insertIndex) {
preItem = current
current = current.next
}
newNode.next = current
preItem.next = newNode
return true
}
removeAt(removeIndex) {
if (removeIndex < 0 || removeIndex >= this.length) return false
this.length -= 1
if (removeIndex === 0) return this.head = this.head.next
let current = this.head,
preItem = null,
index = 0;
while (index++ < removeIndex) {
preItem = current
current = current.next
}
return preItem.next = current.next
}
remove(data) {
const index = this.indexOf(data)
return this.removeAt(index)
}
update(data, updateIndex) {
if (updateIndex < 0 || updateIndex >= this.length) return false
let current = this.head,
index = 0;
while (index++ < updateIndex) {
current = current.next
}
return current.data = data
}
get(getIndex) {
if (getIndex < 0 || getIndex >= this.length) return false
let current = this.head,
index = 0;
while (index++ < getIndex) {
current = current.next
}
return current.data
}
indexOf(data) {
let current = this.head,
index = 0;
while (current) {
if (JSON.stringify(current.data) === JSON.stringify(data)) return index
current = current.next
index += 1
}
return -1
}
toStringOrArray(type = 'string', placeholder = ' ') {
let current = this.head,
listString = '';
if (type === 'array') listString = []
while (current) {
if (type === 'string') listString += current.data + placeholder
else listString.push(current.data)
current = current.next
}
return listString
}
isEmpty() { return this.length === 0 }
size() { return this.length }
}
const asd = new ListSelf()
asd.append(0)
asd.append(1)
asd.append(2)
asd.append(3)
asd.remove(90)
console.log(asd.toStringOrArray('string'))