forked from abhishuk12/hackoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashMap.java
141 lines (115 loc) · 3.25 KB
/
HashMap.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
public class HashMap {
private final int hsize;
private final LinkedList[] buckets;
public HashMap(int hsize) {
buckets = new LinkedList[hsize];
for (int i = 0; i < hsize; i++) {
buckets[i] = new LinkedList();
// Java requires explicit initialization of each object
}
this.hsize = hsize;
}
public int hashing(int key) {
int hash = key % hsize;
if (hash < 0) {
hash += hsize;
}
return hash;
}
public void insertHash(int key) {
int hash = hashing(key);
buckets[hash].insert(key);
}
public void deleteHash(int key) {
int hash = hashing(key);
buckets[hash].delete(key);
}
public void displayHashtable() {
for (int i = 0; i < hsize; i++) {
System.out.printf("Bucket %d :", i);
System.out.println(buckets[i].display());
}
}
public static class LinkedList {
private Node first;
public LinkedList() {
first = null;
}
public void insert(int key) {
if (isEmpty()) {
first = new Node(key);
return;
}
Node temp = findEnd(first);
temp.setNext(new Node(key));
}
private Node findEnd(Node n) {
while (n.getNext() != null) {
n = n.getNext();
}
return n;
}
public Node findKey(int key) {
if (!isEmpty()) {
Node temp = first;
if (temp.getKey() == key) return temp;
while ((temp = temp.getNext()) != null) {
if (temp.getKey() == key) return temp;
}
}
return null;
}
public void delete(int key) {
if (!isEmpty()) {
if (first.getKey() == key) {
Node next = first.next;
first.next = null; // help GC
first = next;
} else {
delete(first, key);
}
}
}
private void delete(Node n, int key) {
if (n.getNext().getKey() == key) {
if (n.getNext().getNext() == null) {
n.setNext(null);
} else {
n.setNext(n.getNext().getNext());
}
} else {
delete(n.getNext(), key);
}
}
public String display() {
return display(first);
}
private String display(Node n) {
if (n == null) {
return "null";
} else {
return n.getKey() + "->" + display(n.getNext());
}
}
public boolean isEmpty() {
return first == null;
}
}
public static class Node {
private Node next;
private final int key;
public Node(int key) {
next = null;
this.key = key;
}
public Node getNext() {
return next;
}
public int getKey() {
return key;
}
public void setNext(Node next) {
this.next = next;
}
}
}