JavaScript数据结构之链表
function defaultEquals (a, b) {
return a===b
}
class Node{
constructor(element) {
this.element = element
this.next=undefined
}
}
class LinkedList {
constructor(equalsFn =defaultEquals) {
this.count = 0
this.head=undefined
this.equalsFn =equalsFn
}
//追加节点到链表最后面
push (el) {
//创建一个节点
const node = new Node(el)
let current
//如果链表的头部不为null
if (this.head == null) {
//新增的节点就是链表头
this.head=node
} else {
//否则从链表头查起
current = this.head
while (current.next!=null) {
current=current.next
}
//把链表的最后一个跟新节点链接起来
current.next=node
}
//链表长度加1
this.count++
}
//获取指定位置的节点
getElement (index) {
if (index>=0&& index<=this.count) {
let node = this.head
for (let i = 0; i < index&&node!=null; i++) {
node=node.next
}
return node
}
return undefined
}
//删除指定位置节点
removeAt (index) {
//锁定删除链表索引范围
if (index >= 0 && index <= this.count) {
let current = this.head
if (index===0) {
this.head=current.next
} else {
//获取指定位置的前一个节点
const previous = this.getElement(index - 1)
//当前索引节点
current = previous.next
//链接目标节点的上一个节点和下一个节点,删除节点完毕
previous.next=current.next
}
this.count--
}
return undefined
}
//插入节点
insert(index,el){
//设置索引边界
if(index>=0&&index<=this.count){
//新建节点
const node=new Node(el)
//当索引为0的时候
if(index===0){
const current=this.head
node.next = current
this.head=node
}else{
//索引不为零的时候
const previous=this.getElement(index-1)
const current =previous.next
node.next=current
previous.next=node
}
this.count++
return true
}
return false
}
//查找索引
indexOf(el){
let current=this.head
for (let i = 0; i < this.count&&this.current!=null; i++) {
if(this.equalsFn(el,current.element)){
return i
}
current=current.next
}
return -1
}
//判断链表长度
size(){
return this.count
}
//判断是否为空
isEmpty(){
return this.count()===0
}
//获取头元素
getHead(){
return this.head
}
//字符串方法
toString () {
if (this.isEmpty()) {
return ''
}
let str = `${this.head.element}`
let current=this.head.next
for (let i = 1; i <this.size()&¤t!=null; i++) {
str += `,${current.element}`
current=current.next
}
return str
}
}
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。