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
}
}
JavaScript之數據結構鏈表
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.