-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathChainingHashTable.java
123 lines (99 loc) · 2.14 KB
/
ChainingHashTable.java
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
122
123
package ds_007_hashtables;
import java.util.LinkedList;
import java.util.List;
public class ChainingHashTable {
private static final int DEFAULT_CAPACITY = 10;
private List<Integer>[] data;
private int capacity;
private int size;
public ChainingHashTable() {
this(DEFAULT_CAPACITY);
}
public ChainingHashTable(int capacity) {
this.capacity = capacity;
init();
}
private void init() {
data = new LinkedList[capacity];
size = 0;
}
public boolean put(int element) {
if(data[hashFunction(element)] == null) {
data[hashFunction(element)] = new LinkedList<>();
}
data[hashFunction(element)].add(element);
size++;
return true;
}
public Integer get(int element) {
return find(element);
}
private Integer find(int element) {
List<Integer> list = data[hashFunction(element)];
if(list != null) {
for(Integer temp : list) {
if(temp.equals(element)) {
return temp;
}
}
}
return null;
}
public Integer remove(int element) {
Integer removed = find(element);
if(removed != null) {
data[hashFunction(element)].remove(removed);
size--;
if( data[hashFunction(element)].isEmpty() ) {
data[hashFunction(element)] = null;
}
}
return removed;
}
private int hashFunction(int element) {
int hashValue = element%capacity;
return hashValue;
}
// trival
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
public void print() {
System.out.print("Hash Table: ");
if(isEmpty()) {
System.out.print("Empty");
} else {
for(int i = 0; i < capacity; i++) {
if(data[i] != null) {
for(Integer temp: data[i]) {
System.out.printf("%2d ", temp);
}
}
}
}
System.out.print("\n");
}
public void printVerbose() {
System.out.print("Hash Table: ");
if(isEmpty()) {
System.out.print("Empty");
} else {
for(int i = 0; i < capacity; i++) {
if(data[i] != null) {
for(Integer temp : data[i]) {
System.out.printf("%2d ", temp);
}
} else {
System.out.print(" - ");
}
}
}
System.out.print("\n");
}
}