Skip to content

Instantly share code, notes, and snippets.

@qwasfun
Created January 9, 2025 16:52
Show Gist options
  • Select an option

  • Save qwasfun/5c56fd07555b092bd8849b06cbb8c722 to your computer and use it in GitHub Desktop.

Select an option

Save qwasfun/5c56fd07555b092bd8849b06cbb8c722 to your computer and use it in GitHub Desktop.
分离链接处理 散列表冲突
import { defaultToString, ValuePair } from './Dictionary.mjs'
import { HashTable } from './HashTable.mjs'
import { LinkList } from './LinkList'
class HashTableSeparateChaining extends HashTable {
constructor(toStrFn = defaultToString) {
this.toStrFn = super(toStrFn)
}
put(key, value) {
if (key != null && value != null) {
const position = this.hashCode(key)
if (this.table[position] == null) {
this.table[position] = new LinkList()
}
this.table[position].push(new ValuePair(key, value))
return true
}
return false
}
get(key) {
const position = this.hashCode(key)
const linkedList = this.table[position]
if (linkedList != null && !linkedList.isEmpty()) {
let current = linkedList.getHead()
while (current != null) {
if (current.element.key === key) {
return current.element.value
}
current = current.next
}
}
return undefined
}
remove() {
const position = this.hashCode(key)
const linkedList = this.table[position]
if (linkedList != null && !linkedList.isEmpty()) {
let current = linkedList.getHead()
while (current != null) {
if (current.element.key === key) {
linkedList.remove(current.element)
if (linkedList.isEmpty()) {
delete this.table[position]
}
return true
}
current = current.next
}
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment