Skip to content

Commit 8f77df3

Browse files
committed
新增解决哈希表地址冲突
1 parent 8e846fa commit 8f77df3

File tree

3 files changed

+71
-3
lines changed

3 files changed

+71
-3
lines changed

散列表(hashMap)/index.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,6 @@ HashTable.prototype.remove = function (key) {
2828
this.table[LoseLoseHashCode(key)] = undefined
2929
}
3030

31-
let hash = new HashTable()
32-
hash.put('heshihao', 99)
31+
32+
3333

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// 上面的会出现地址冲突 所以我们需要在每个地址上让他成为一个链表
2+
function HashTable() {
3+
this.table = []
4+
}
5+
6+
let ValuePair = function (key, value) {
7+
this.key = key
8+
this.value = value
9+
this.toString = function () {
10+
return '[' + this.key + ' - ' + this.value + ']';
11+
}
12+
}
13+
14+
// 重写put 方法
15+
HashTable.prototype.put = function (key, value) {
16+
var postition = LoseLoseHashCode(key)
17+
if (this.table[postition] == undefined) {
18+
this.table[postition] = new linklist()
19+
}
20+
// append 参见链表数据结构
21+
this.table[postition].append(new ValuePair(key, value))
22+
}
23+
24+
// 重写get方法
25+
HashTable.prototype.get = function (key) {
26+
let pos = LoseLoseHashCode(key)
27+
if (this.table[pos] != undefined) {
28+
// getHead 参见链表数据结构
29+
let current = this.table[pos].getHead()
30+
while (current.next) {
31+
if (current.ele.key == key) {
32+
return current.ele.value
33+
}
34+
current = current.next
35+
}
36+
if (current.ele.key == key) {
37+
return current.ele.value
38+
}
39+
}
40+
return undefined
41+
}
42+
43+
// 重写移除方法
44+
HashTable.prototype.remove = function (key) {
45+
let pos = LoseLoseHashCode(key)
46+
if (this.table[pos] !== undefined) {
47+
let current = new linklist.getHead()
48+
while (current.next) {
49+
if (current.ele.key == key) {
50+
this.table[pos].remove(current.ele)
51+
if (table[position].isEmpty()) {
52+
table[position] = undefined;
53+
}
54+
return true
55+
}
56+
current = current.next
57+
}
58+
if (current.element.key === key) { //{16}
59+
this.table[pos].remove(current.element);
60+
if (this.table[pos].isEmpty()) {
61+
this.table[pos] = undefined;
62+
}
63+
return true;
64+
}
65+
} else {
66+
return false
67+
}
68+
}

链表数据结构(linklist)/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ LinkedList.prototype.remove = function (ele) {
9898
// 元素所在的位置
9999
LinkedList.prototype.indexOf = function (ele) {
100100
let current = this.head;
101-
let index = -1;
101+
let index = 0;
102102
while (current) {
103103
if (current.item == ele) {
104104
return index

0 commit comments

Comments
 (0)