-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMapCustom
More file actions
88 lines (82 loc) · 1.7 KB
/
HashMapCustom
File metadata and controls
88 lines (82 loc) · 1.7 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
public Node<K,V> {
K key;
V value;
Node<K,V> next;
Node<K,V>(K k, V v, Node<K,V> n) {
this.key = k;
this.value = v;
this.next = n;
}
}
public class HashMapCustom<K,V> {
Node<K,V>[] arr;
HashMapCustom<K,V>() {
arr = new Node[100];
}
void put(K key, V value) {
if(k==null)
return;
int hashValue = hash(k);
curr = arr[hashValue];
temp = curr;
if(curr==null) {
Node<K,V> newNode = new Node<K,V>(key,value,null);
arr[hashValue] = newNode;
}
else{
boolean inserted = false;
while(curr!=null) {
if(curr.key == newNode.key) {
curr.value = newNode.value;
inserted = true;
}
curr = curr.next;
}
if(inserted == false) {
Node<K,V> newNode = new Node<K,V>(key,value,null);
newNode.next = temp;
arr[hash] = newNode;
}
}
}
public V get(K key) {
int hashValue = hash(key);
if(arr[hashValue]==null)
return null;
else {
curr = arr[hashValue];
while(curr!=null) {
if(curr.key == key)
return curr.value;
else {
curr = curr.next;
}
}
return null;
}
}
public void delete(K key) {
int hashValue = hash(key);
if(arr[hashValue]==null)
return;
curr = arr[hashValue];
prev = null;
while(curr!=null) {
if(curr.key == key) {
if(prev==null) {
curr = curr.next;
arr[hashValue] = curr;
return;
}
else {
prev.next = curr.next;
return;
}
}
else {
prev = curr;
curr = curr.next;
}
}
}
}