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
+ }
0 commit comments