JSデータ構造一方向チェーンテーブル
6259 ワード
たんほうこうチェーンテーブル
注意:
簡単な例を挙げます.
チェーンテーブルクラスメソッド
class LinkedList {
constructor() {
this.head = null
this.length = 0
}
append(element) {
const newNode = new Node(element);
//
if (!this.head) {
this.head = newNode
} else {
let current = this.head;
while (current.next) {
current = current.next
}
current.next = newNode
}
this.length++
}
insert(position, element) {
//
if (position < 0 || position > this.length) return false
//
const newNode = new Node(element)
//
if (position === 0) {
newNode.next = this.head
this.head = newNode
} else {
let index = 0
let current = this.head
let previous = null
while (index++ < position) {
previous = current
current = current.next
}
previous.next = newNode
newNode.next = current
}
this.length++
return true
}
get(position) {
if (position < 0 || position > this.length - 1) return null
//
let index = 0
let current = this.head
while (index++ < position) {
current = current.next
}
return current.element
}
indexOf(element) {
//
let current = this.head
let index = 0
//
while (current) {
if (current.element === element) {
return index
}
index++
current = current.next
}
return -1
}
update(positon, element) {
// position ,
const result = this.removeAt(positon)
// position,
this.insert(positon, element)
return result
}
removeAt(position) {
if (position < 0 || position > this.length - 1) return null
//
let current = this.head
let previous = null
let index = 0
//
if (position === 0) {
this.head = current.next
} else {
while (index++ < position) {
previous = current
current = current.next
}
previous.next = current.next
}
this.length--
return current.element
}
remove(element) {
//
const index = this.indexOf(element)
if (index === -1) return
//
this.removeAt(index)
}
isEmpty() {
return this.length === 0
}
size() {
return this.length
}
}
メソッドが成功したかどうかをテスト
const linkedList = new LinkedList()
linkedList.append('aaa')
linkedList.append('bbb')
linkedList.append('ccc')
linkedList.append('ddd')
console.log(linkedList)// length 4 , node
linkedList.insert(1, 'abc')
linkedList.insert(3, 'cba')
console.log(linkedList)// length 6 , node
console.log(linkedList.get(1))// abc
console.log(linkedList.get(3))// cba
console.log(linkedList.indexOf('abc'))// 1
console.log(linkedList.indexOf('cba'))// 3
console.log(linkedList.indexOf('asdsd'))// -1( -1)
console.log(linkedList.removeAt(3))// cba
console.log(linkedList.removeAt(1))// abc
console.log(linkedList)// length 4
console.log(linkedList.update(1, 'npc'))// bbb( : , undefined, , )
console.log(linkedList)// bbb npc, length 4
linkedList.remove('aaa')
console.log(linkedList)// length 3
console.log(linkedList.isEmpty())// false
console.log(linkedList.size())// 3