Skip to content

Commit 697d25b

Browse files
author
Ray
committed
Add nested linked list and node class to HashMap.java
1 parent 1e64653 commit 697d25b

File tree

1 file changed

+108
-3
lines changed

1 file changed

+108
-3
lines changed

DataStructures/HashMap/Hashing/HashMap.java

+108-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package DataStructures.HashMap.Hashing;
22

3-
43
class HashMap {
54
private int hsize;
65
private LinkedList[] buckets;
@@ -36,8 +35,114 @@ public void deleteHash(int key) {
3635
public void displayHashtable() {
3736
for (int i = 0; i < hsize; i++) {
3837
System.out.printf("Bucket %d :", i);
39-
buckets[i].display();
38+
System.out.println(buckets[i].display());
4039
}
4140
}
42-
41+
42+
public static class LinkedList {
43+
private Node first;
44+
45+
public LinkedList() {
46+
first = null;
47+
}
48+
49+
public void insert(int key){
50+
if(isEmpty()) {
51+
first = new Node(key);
52+
return;
53+
}
54+
55+
Node temp = findEnd(first);
56+
temp.setNext(new Node(key));
57+
}
58+
59+
private Node findEnd(Node n) {
60+
if(n.getNext() == null) {
61+
return n;
62+
} else {
63+
return findEnd(n.getNext());
64+
}
65+
}
66+
67+
public Node findKey(int key) {
68+
if(!isEmpty()) {
69+
return findKey(first, key);
70+
} else {
71+
System.out.println("List is empty");
72+
return null;
73+
}
74+
75+
}
76+
77+
private Node findKey(Node n, int key) {
78+
if(n.getKey() == key) {
79+
return n;
80+
} else if(n.getNext() == null) {
81+
System.out.println("Key not found");
82+
return null;
83+
} else {
84+
return findKey(n.getNext(),key);
85+
}
86+
}
87+
88+
public void delete(int key) {
89+
if(!isEmpty()) {
90+
if(first.getKey() == key) {
91+
first = null;
92+
} else {
93+
delete(first,key);
94+
}
95+
} else {
96+
System.out.println("List is empty");
97+
}
98+
}
99+
100+
private void delete(Node n, int key) {
101+
if(n.getNext().getKey() == key) {
102+
if(n.getNext().getNext() == null) {
103+
n.setNext(null);
104+
} else {
105+
n.setNext(n.getNext().getNext());
106+
}
107+
}
108+
}
109+
110+
public String display() {
111+
return display(first);
112+
}
113+
114+
private String display(Node n) {
115+
if(n == null) {
116+
return "null";
117+
} else {
118+
return n.getKey() + "->" + display(n.getNext());
119+
}
120+
}
121+
122+
public boolean isEmpty() {
123+
return first == null;
124+
}
125+
}
126+
127+
public static class Node {
128+
private Node next;
129+
private int key;
130+
131+
public Node(int key) {
132+
next = null;
133+
this.key = key;
134+
}
135+
136+
public Node getNext() {
137+
return next;
138+
}
139+
140+
public int getKey() {
141+
return key;
142+
}
143+
144+
public void setNext(Node next) {
145+
this.next = next;
146+
}
147+
}
43148
}

0 commit comments

Comments
 (0)