-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathSeparateChainHashTable.java
More file actions
121 lines (94 loc) · 2.79 KB
/
Copy pathSeparateChainHashTable.java
File metadata and controls
121 lines (94 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package ch05;
import java.util.LinkedList;
import java.util.List;
/**
* Created by cookfront on 2017/3/5.
*/
public class SeparateChainHashTable<AnyType> {
private static final int DEFAULT_TABLE_SIZE = 10;
private List<AnyType>[] theLists;
private int currentSize;
public SeparateChainHashTable() {
this(DEFAULT_TABLE_SIZE);
}
public SeparateChainHashTable(int size) {
theLists = new LinkedList[nextPrime(size)];
for (int i = 0; i < theLists.length; i++) {
theLists[i] = new LinkedList<AnyType>();
}
}
public void insert(AnyType x) {
List<AnyType> whichList = theLists[myhash(x)];
if (!whichList.contains(x)) {
whichList.add(x);
if (++currentSize > theLists.length) {
rehash();
}
}
}
public void remove(AnyType x) {
List<AnyType> whichList = theLists[myhash(x)];
if (whichList.contains(x)) {
whichList.remove(x);
currentSize--;
}
}
public boolean contains(AnyType x) {
List<AnyType> whichList = theLists[myhash(x)];
return whichList.contains(x);
}
public void makeEmpty() {
for (int i = 0; i < theLists.length; i++)
theLists[i].clear();
currentSize = 0;
}
public static int hash(String key, int tableSize) {
int hashVal = 0;
for (int i = 0; i < key.length(); i++)
hashVal = 37 * hashVal + key.charAt(i);
hashVal %= tableSize;
if (hashVal < 0)
hashVal += tableSize;
return hashVal;
}
private void rehash() {
List<AnyType> [] oldLists = theLists;
// Create new double-sized, empty table
theLists = new List[nextPrime(2 * theLists.length)];
for (int j = 0; j < theLists.length; j++)
theLists[j] = new LinkedList<>();
// Copy table over
currentSize = 0;
for (List<AnyType> list : oldLists)
for (AnyType item : list)
insert(item);
}
private int myhash(AnyType x) {
int hashVal = x.hashCode();
hashVal %= theLists.length;
if (hashVal < 0) {
hashVal += theLists.length;
}
return hashVal;
}
private static int nextPrime(int n) {
if (n % 2 == 0)
n++;
for (; !isPrime( n ); n += 2)
;
return n;
}
private static boolean isPrime(int n) {
if (n == 2 || n == 3)
return true;
if (n == 1 || n % 2 == 0)
return false;
for (int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
public static void main(String ...args) {
System.out.println("test");
}
}