Skip to content

Add nested linked list and node class to HashMap.java #1391

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 7, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 110 additions & 5 deletions DataStructures/HashMap/Hashing/HashMap.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package DataStructures.HashMap.Hashing;


class HashMap {
public class HashMap {
private int hsize;
private LinkedList[] buckets;

Expand Down Expand Up @@ -36,8 +35,114 @@ public void deleteHash(int key) {
public void displayHashtable() {
for (int i = 0; i < hsize; i++) {
System.out.printf("Bucket %d :", i);
buckets[i].display();
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) {
if(n.getNext() == null) {
return n;
} else {
return findEnd(n.getNext());
}
}

public Node findKey(int key) {
if(!isEmpty()) {
return findKey(first, key);
} else {
System.out.println("List is empty");
return null;
}

}

private Node findKey(Node n, int key) {
if(n.getKey() == key) {
return n;
} else if(n.getNext() == null) {
System.out.println("Key not found");
return null;
} else {
return findKey(n.getNext(),key);
}
}

public void delete(int key) {
if(!isEmpty()) {
if(first.getKey() == key) {
first = null;
} else {
delete(first,key);
}
} else {
System.out.println("List is empty");
}
}

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());
}
}
}

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 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;
}
}
}